daydayup
daydayup

Reputation: 2317

How do I correctly find a value from part of a vector?

I was expecting the following code should print out only "2 is found", however it prints out both. The second one should not happen because 4 is not in the first 3 elements of the vector. Where did I make the mistake?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> a = {1,2,3,4,5};
    if(find(a.begin(),a.begin()+3,2) != a.end()) cout << "2 found" << endl;
    if(find(a.begin(),a.begin()+3,4) != a.end()) cout << "4 found" << endl;
}

Result:

2 found
4 found

Upvotes: 1

Views: 45

Answers (2)

Ani Menon
Ani Menon

Reputation: 28257

Change find(a.begin(),a.begin()+3,2) != a.end() to find(a.begin(),a.begin()+3,2) != a.begin()+3

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> a = {1,2,3,4,5};
    if(find(a.begin(),a.begin()+3,2) != a.begin()+3) cout << "2 found" << endl;
    if(find(a.begin(),a.begin()+3,4) != a.begin()+3) cout << "4 found" << endl;

}

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106236

find returns the end/"last" value you passed it if the value is not found, which in this case is not a.end(). The code should compare a la ... != a.begin() + 3....

Upvotes: 3

Related Questions