[英]STL std::find() C++
在下面的代碼中,我將向量聲明為{1,2,3,4,5}
。
使用 STL std::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;
}
OUTPUT:
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
沒有找到請求的值(因為它出現在這里),它返回你給它的結束迭代器(不是完整向量的結束迭代器),在這種情況下指向你所在的元素尋找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.