Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL std::find() C++

In the below code I declared a vector as {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.

But here for both, iterators are return pointing to 5. Why is that since the range is only from 1 to 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!
like image 215
Rishi K. Avatar asked May 21 '26 04:05

Rishi K.


1 Answers

std::find just returns the iterator passed as the 2nd argument when the element is not found. So it returns the iterators as arr.begin()+4 or arr.end()-1 in your code.

You shouldn't compare it with std::end, e.g.

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;
like image 139
songyuanyao Avatar answered May 23 '26 18:05

songyuanyao