How to find out if an item is present in a std::vector with C++

1 Answer

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

int main() {
    std::vector<int> vec = {1, 3, 21, 9, 88, 6, 7, 2, 45}; 
    int item = 88;

    // Print result using std::boolalpha for better readability
    std::cout << std::boolalpha << (std::find(vec.begin(), vec.end(), item) != vec.end()) << "\n";

    // Print yes/no message
    std::cout << (std::find(vec.begin(), vec.end(), item) != vec.end() ? "yes\n" : "no\n");

    // Conditional output
    if (std::find(vec.begin(), vec.end(), item) != vec.end()) {
        std::cout << "Found\n";
    } else {
        std::cout << "Not found\n";
    }
}

 
 
/*
run:
 
true
yes
Found
 
*/
   
 

 



answered May 11, 2025 by avibootz
...