简体   繁体   English

STL std::find() C++

[英]STL std::find() C++

In the below code I declared a vector as {1,2,3,4,5} .在下面的代码中,我将向量声明为{1,2,3,4,5}

Using the STL std::find() , I am trying to find 5 in the vector ranging from arr.begin() to arr.end()-1 or arr.begin() to arr.begin()+4 which is the same range from 1 to 4 .使用 STL std::find() ,我试图在从arr.begin()arr.end()-1arr.begin()arr.begin()+4的向量中找到5 ,即相同的范围从14

But here for both, iterators are return pointing to 5 .但在这里,迭代器都返回指向5 Why is that since the range is only from 1 to 4 ?为什么会这样,因为范围只有14

#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: OUTPUT:

1 2 3 4 
1 2 3 4 
5 Found!
5 Found!

std::find just returns the iterator passed as the 2nd argument when the element is not found.当未找到元素时, std::find仅返回作为第二个参数传递的迭代器。 So it returns the iterators as arr.begin()+4 or arr.end()-1 in your code.因此,它在您的代码中将迭代器作为arr.begin()+4arr.end()-1返回。

You shouldn't compare it with std::end , eg您不应该将其与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;

It is because if std:find does not find the requested value (as it occurs here), it returns the end iterator you give to it (not the end iterator of the full vector), which in this case points to the element you are looking for.这是因为如果std:find没有找到请求的值(因为它出现在这里),它返回你给它的结束迭代器(不是完整向量的结束迭代器),在这种情况下指向你所在的元素寻找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM