2012-07-09 22 views
1

我有一個像下面如何檢查這是否是std :: list的最後一個成員?

typedef std::list<std::string> SegmentValue; 

然後在迭代我需要檢查,如果這是最後一次迭代的列表。

 for(Field::SegmentValue::const_iterator it = m_segmentValue.begin();It != 
      m_segmentValue.end();It++){ 
       if((segIt + 1) == m_segmentValue.end())//last iteration 
       ... 
     } 

,但我在編譯得到錯誤:

error C2678: binary '+' : no operator found which takes a left-hand operand of type 'std::list<_Ty>::_Const_iterator<_Secure_validation>' 

我怎麼能檢查,如果這是最後itration?

回答

4

您不能使用二進制+-運算符與std::list迭代器。 std::list迭代器是雙向迭代器,但它們不是隨機訪問迭代器,這意味着您不能將它們移動任意的常量值。

使用一元++--代替

Field::SegmentValue::const_iterator it_last = m_segmentValue.end(); 
--it_last; 

現在it_last是最後一個元素的迭代器。只要確保它仍然有效。如果您沒有對容器做任何迭代器無效修改,則可以預先計算it_last並在循環中使用它。否則,您必須根據需要重新計算它。

事實上,在泛型算法它始終是一個好主意,使用--++迭代器更喜歡儘可能地(而不是二進制+ 1- 1),因爲它減少了你的算法的要求:二進制+-需要隨機訪問迭代器,而++--雙向個。

0

試試這個:

Field::SegmentValue::const_iterator next = it; ++next; 
// or in C++11: 
// Field::SegmentValue::const_iterator next = std::next(it); 
if(next == m_segmentValue.end()) //last iteration 

列表迭代器Bidirectional,不RandomAccess所以他們不支持operator+

0

std :: list迭代器不是隨機訪問,它們是雙向的。運營商+不受支持。你需要使用std :: vector來做類似的事情。

2

使用std::next

if (std::next(segIt) == m_segmentValue.end()) ... 

如果您使用C++ 03,你可以隨便寫next自己:

template<typename T> T next(T it, typename std::iterator_traits<T>::difference_type n = 1) { 
    std::advance(it, n); 
    return it; 
} 
+0

我寧願在循環前使用'std :: prev'在'end()'上預先計算它。 – jrok 2012-07-09 15:06:01

1

像這樣的東西可能:

Field::SegmentValue::const_iterator last = m_segmentValue.end() 
--last; 

for(Field::SegmentValue::const_iterator it = m_segmentValue.begin(); 
    It != m_segmentValue.end(); 
    It++) { 

     if(It == last) { 
      // last iteration 
     }  
    } 

您只能使用隨機訪問迭代器進行算術運算。 std::list的迭代器是雙向的。

請參閱here瞭解您可以或不可以對各種類別的迭代器執行的操作。

0

如何:

if (&*it == &*(m_segmentValue.rbegin())) 

即,比較段的地址。

相關問題