簡體   English   中英

迭代器和2d向量

[英]Iterator and 2d vector

vector< vector<int> >::iterator temp = mincost.end();
vector<int> a = *temp;
if ( *temp != *(temp--) ) 
    return 0;

mincost是一個2d向量,我想獲取此vector<int>的最后一個vector<int>以及last-- 我對迭代器不是很了解:)。 幫我 !! :D Thx ^^

minconst.end()指向向量minconst 的最后一個元素; 它不指向向量中的最后一個元素。

由於您需要最后兩個元素,因此應該首先進行測試以確保向量中確實包含兩個元素,否則不可避免地會遇到問題。 然后,訪問向量中的最后一個元素僅是*(minconst.end() - 1) ,依此類推。

《 C ++參考》還對迭代器進行了描述

通常,了解迭代器可能會有所幫助。

快速的Google搜索會帶來很多好的參考,其中最重要的是http://www.cppreference.com/wiki/stl/iterators

祝好運!

如果您不熟悉STL容器,則可以將end()迭代器想像成C字符串中的'\\ 0'字符-它們定義了結尾在哪里,但是它們攜帶的實際值沒有用。 如果取消引用最終迭代器,則將導致垃圾,或者很可能是異常。

嘗試這個:

       if (!mincost.empty())
       {
             //it contains atleast one 1-d vector and the 'end' iterator.
             iter = mincost.end();
             --iter;
             //dereference iter here.
       }

一旦您對迭代器感到滿意,請查找reverse_iterator。 正如Effo所說,它們是這里最好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM