[英]STL algorithms and const_iterators
今天我寫了一個小謂詞來查找容器中的匹配符號。
但是我遇到了一個問題:我想在一個類的const方法中的std::find_if
調用中使用這個謂詞,在一個容器中搜索這個類的成員。
但我只是注意到std::find
和std::find_if
都不能在const_iterators
上運行!
我檢查了一些C ++引用,似乎沒有std::find
或std::find_if
版本接受/返回const_iterators
。 我只是無法理解為什么,因為從我所看到的,這些算法無法修改迭代器引用的對象。
以下是在SGI實現中記錄的std::find
的方法:
返回[first,last]范圍內的第一個迭代器i,使得* i == value。 如果不存在這樣的迭代器,則返回last。
對於給定的容器, std::find
和std::find_if
肯定可以在*::const_iterator
上運行。 您是否偶然看到這些功能的簽名,並誤解它們?
template <class InputIterator, class Type>
InputIterator find(InputIterator first, InputIterator last, const Type& val);
請注意,這里的InputIterator
只是模板類型參數的名稱,任何const_iterator
都將滿足它的要求。
或者,也許,你混淆const_iterator
(即一個迭代器引用一個常量的值)與const
迭代器(即一個迭代器本身是const
)?
std::find
和std::find_if
都將迭代器類型作為模板參數,因此它們肯定可以在const_iterators
運行。 只是為了一個簡單的例子:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> x;
std::fill_n(std::back_inserter(x), 20, 2);
x.push_back(3);
std::vector<int>::const_iterator b = x.begin();
std::vector<int>::const_iterator e = x.end();
std::vector<int>::const_iterator p = std::find(b, e, 3);
std::cout << *p << " found at position: " << std::distance(b, p) << "\n";
return 0;
}
這應該由任何正常運行的C ++編譯器接受,並產生如下結果:
3發現在位置:20
我剛遇到同樣的問題。 我有一個在成員向量上調用find_if
的成員函數,當我嘗試使用成員函數const
時,編譯器給了我一個錯誤。 事實證明,這是因為我將find_if
的返回值find_if
iterator
而不是const_iterator
。 導致編譯器假設find_if
的參數也必須是iterator
而不是const_iterator
,它無法從const
成員向量中獲取。
如果你有任何機會出於與我相同的原因:
error: no matching function for call to ‘find(std::vector<int>::const_iterator, std::vector<int>::const_iterator, int)’
它與const_iterator
沒有任何關系。 你可能只是忘了#include <algorithm>
:-)
我剛剛遇到此代碼的問題:
std::string str;
std::string::const_iterator start = str.begin();
std::string::const_iterator match = std::find(start, str.end(), 'x');
錯誤是“std :: find沒有匹配的重載”。
我需要的修復是使用cend()。 令人困惑的是cbegin()不是必需的,我不確定為什么轉換是可以的(隱式)而不是end()作為函數參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.