简体   繁体   中英

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

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... .

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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