2017-02-16 31 views
2

有時候我會想用算法庫中函數返回的迭代器。我在修改函數和非修改函數之間出現問題。原因在非修改功能我想使用const_iterator。作爲玩具的例子:是否有make_const_iterator?

vector<int> v = { 1, 8, 7, 4, 3, 6, 2, 5 }; 
auto it = partition(begin(v), end(v), bind(greater<int>(), placeholders::_1, 3)); 

cout << (find(cbegin(v), it, 13) != cend(v)) << endl; 

當我嘗試編譯此代碼我得到的錯誤:

no matching function for call to find(std::vector<int>::const_iterator, __gnu_cxx::__normal_iterator<int*, std::vector<int> >&, int)

我快到的問題是唯一的轉換過程中,我能找到的是潛在的昂貴: auto cit = next(cbegin(v), distance(begin(v), it))

有沒有辦法讓這項工作?或者我堅持轉換或只使用非const_iterator

+0

只是一個先發制人的評論,我知道我可以只使用'find'直接'v'。我不想找一個更好的方式來寫我的玩具的例子;我正在尋找解決它解釋的問題的解決方案。 –

+0

你是否嘗試過從正常的構造一個const_iterator? – rubenvb

+0

我們是否假設原始容器的類型是未知的?如果不是這樣,'decltype(v):: const_iterator(it)'就行。在你提出的解決方案中使用cvegin(v)似乎意味着你可以訪問'v',而不僅僅是迭代器。 –

回答

3

它的成本要低得多,以簡單的可變迭代器轉換爲一個常數迭代器:

cout << (find(cbegin(v), vector<int>::const_iterator{it}, 13) 
     != cend(v)) << endl; 

一個可變的迭代器應該總是被強制爲一個常數迭代器。

編輯:我發現標準的一部分,保證迭代器可轉換爲一個常量迭代器。

表96在第23.2節 「集裝箱要求」 規定了在表達X::iterator結果:

any iterator category that meets the forward iterator requirements. convertible to X::const_iterator.

+1

有沒有保證這樣的轉換? –

+1

@ Cheersandhth.-Alf請看這裏:http://stackoverflow.com/a/7759474/1294207 –

+1

@FantasticMrFox:太棒了,謝謝。我相信好機器人。但是一個標準的參考。本來可以解決這個問題的。 –

4

您可以指定模板參數:

find<decltype(cbegin(v))>(cbegin(v), it, 13) != cend(v) 

Demo

+2

我看到這個錯誤實際上是因爲我在模板扣除find時造成模糊。所以這和其他例子一樣,強制演員陣容。是否有任何聲明表明此類演員陣容是合法的,而不僅僅是實施定義? –

1

有三種方法。

第一種是寫

cout << (find(begin(v), it, 13) != cend(v)) << endl; 
       ^^^^^ 

第二個是寫

cout << (find(cbegin(v), static_cast<std::vector<int>::const_iterator>(it) 
, 13) != cend(v)) << endl; 

或更短

cout << (find(cbegin(v), static_cast<decltype(v.cbegin())>(it) 
, 13) != cend(v)) << endl; 

,第三個是寫

cout << (find<std::vector<int>>::const_iterator>(cbegin(v), it, 13) != cend(v)) << endl; 

或更短

cout << (find<decltype(v.cbegin())>(cbegin(v), it, 13) != cend(v)) << endl; 
+0

是的,我在這個問題中提到** 1 **是不可取的。其他2個選項都有效地轉換爲'const_iterator'(我不知道你可以做什麼)。標準中是否有明確允許這樣做的內容? –

+1

@JonathanMee請參閱表96 - 容器需求有關迭代器的行。 –