2013-06-04 74 views
6

我目前正在學習STL,並且對find和const iterators有一些不確定性。 比方說,我有一個查找功能:C++ STL,常量迭代器,find()

some_stl_container::const_iterator found = myContainer.find(value); 

之後,我應該檢查什麼,我得到了found對另一常量性,或者是 有效做出對證簡單的迭代器。 基本上會有這樣做有什麼區別:這

if(found!=myContainer.cend()) 

if(found!=myContainer.end()) 

第一看上去更加準確的(至少對我來說),但第二個應該正常工作過,對吧?

+0

[const to non-const iterator_comparatoron,它們是否有效]的可能重複(http://stackoverflow.com/questions/16900498/const-to-non-const-iterator-comparisons-are-they-有效的) – juanchopanza

+0

考慮到cend在C++ 11之前並不存在,所以必須有*某種方式來實現它。 –

回答

8

所有標準庫容器滿足Container::iterator可轉換爲Container::const_iterator的要求。所以兩個比較都是有效的,並且會得到相同的結果。

§23.2.1 - 表96

X::iterator...滿足前向迭代 要求的迭代器類別。可兌換爲X::const_iterator

+0

有趣的是,我只是試圖找到在標準中確認'x.cend()== X :: const_iterator(x.end())'。並沒有找到一個(可能我錯過了一些明顯的邏輯結論)。按照定義'x.cend()== const_cast (x).end()'但我不明白這是如何證明第一個斷言。 –

+0

@SergeDundich我不知道我理解你的問題。我清楚地指出,在容器方面,'iterator'可以轉換爲'const_iterator'。如果你問什麼允許我們使用'operator =='比較2個迭代器,請參考我的[本答案](http://stackoverflow.com/a/16901637/241631)。 – Praetorian

1

檢查你的迭代器是否與myContainer.end()不同。 cendcbegin方法只是在這裏明確地獲取const迭代器,所以在你的情況下沒有區別。

需要注意的是,你可以在C++ 11做auto found = myContainer.find(value)推斷迭代器類型,而且有些人會說,標準庫是正確的名稱(不STL)。

+1

關於你的第二條評論:http://en.wikipedia.org/wiki/Standard_Template_Library – lightxbulb

+0

我的意思是http://en.wikipedia.org/wiki/C%2B%2B_Standard_Library這實際上與原始STL不同(參見http://stackoverflow.com/questions/5205491/whats-this-stl-vs-c-standard-library-fight-all-about)但這是一個有鬍子的純粹論者:p –

+0

@lightxbulb:正如你鏈接的文章STL是一個古老的圖書館,它激發了現代標準圖書館的部分內容。你的問題特別是關於C++ 11標準庫,而不是STL(因爲STL容器沒有'cend'函數)。 –