Ris*_* K. 2 c++ algorithm containers stl find
在下面的代码中,我将向量声明为{1,2,3,4,5}
。
使用STL std::find()
,我试图在从到或到 的5
向量中找到与从到相同的范围。arr.begin()
arr.end()-1
arr.begin()
arr.begin()+4
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 2 3 4
1 2 3 4
5 Found!
5 Found!
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)