在下面的代码中,我将一个向量声明为{1,2,3,4,5}
.
使用 STLstd::find()
,我试图在从arr.begin()
到arr.end()-1
或从arr.begin()
到arr.begin()+4
的向量中找到5
,从1
到4
的范围相同。
但在这里,迭代器都返回指向5
。为什么会这样,因为范围只有从1
到4
?
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
int main () {
vector<int> arr {1,2,3,4,5};
// TEST
for_each(arr.begin(), arr.begin()+4, [](const int &x) { cerr << x << " "; }); cerr << endl;
for_each(arr.begin(), arr.end()-1, [](const int &x) { cerr << x << " "; }); cerr << endl;
auto it1 {std::find(arr.begin(), arr.begin()+4, 5)};
auto it2 {std::find(arr.begin(), arr.end()-1, 5)};
if (it1 != arr.end())
cout << *it1 << " Found!" << endl;
else
cout << "NOT Found!" << endl;
if (it2 != arr.end())
cout << *it2 << " Found!" << endl;
else
cout << "NOT Found!" << endl;
return 0;
}
输出:
1 2 3 4
1 2 3 4
5 Found!
5 Found!
std::find
只返回在找不到元素时作为第二个参数传递的迭代器。因此,它将迭代器作为代码中的arr.begin()+4
或arr.end()-1
返回。
你不应该把它与std::end
进行比较,例如
if (it1 != arr.begin()+4)
cout << *it1 << " Found!" << endl;
else
cout << "NOT Found!" << endl;
if (it2 != arr.end()-1)
cout << *it2 << " Found!" << endl;
else
cout << "NOT Found!" << endl;
这是因为如果std:find
找不到请求的值(如此处发生(,它将返回您提供给它的结束迭代器(而不是完整向量的结束迭代器(,在这种情况下,该迭代器指向您要查找的元素。