How to check if a vector contains a value in C++

3 Answers

0 votes
#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    std::vector<int> v = { 5, 7, 1, 0, 9, 3, 8 };
    int val = 3;
 
    if (std::count(v.begin(), v.end(), val)) {
        std::cout << "found";
    }
    else {
        std::cout << "Not found";
    }
}




/*
run:

found

*/

 



answered Feb 25, 2022 by avibootz
edited Jan 18, 2023 by avibootz
0 votes
#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    std::vector<int> v = { 5, 7, 1, 0, 9, 3, 8 };
    int val = 3;
 
    if (std::find(v.begin(), v.end(), val) != v.end()) {
        std::cout << "found";
    }
    else {
        std::cout << "Not found";
    }
}




/*
run:

found

*/

 



answered Feb 25, 2022 by avibootz
edited Jan 18, 2023 by avibootz
0 votes
#include <vector>
#include <algorithm>
#include <iostream>

bool Contains(const std::vector<int> &v, int x) {
    return std::find(v.begin(), v.end(), x) != v.end();
}

int main() {
    std::vector<int> v = {5, 7, 1, 0, 9, 3, 8};
    int val = 9;

    std::cout << (Contains(v, val) ? "yes": "no");
}




/*
run:

yes

*/


 



answered Jan 18, 2023 by avibootz

Related questions

1 answer 175 views
1 answer 132 views
1 answer 166 views
1 answer 159 views
1 answer 153 views
...