有時候我會想用算法庫中函數返回的迭代器。我在修改函數和非修改函數之間出現問題。原因在非修改功能我想使用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
?
只是一個先發制人的評論,我知道我可以只使用'find'直接'v'。我不想找一個更好的方式來寫我的玩具的例子;我正在尋找解決它解釋的問題的解決方案。 –
你是否嘗試過從正常的構造一個const_iterator? – rubenvb
我們是否假設原始容器的類型是未知的?如果不是這樣,'decltype(v):: const_iterator(it)'就行。在你提出的解決方案中使用cvegin(v)似乎意味着你可以訪問'v',而不僅僅是迭代器。 –