How to use STL binary search algorithm in C++

1 Answer

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

int main() { 
    std::vector <int> vec { 4, 9, 10, 5, 80, 59, 27, 99, 100, 30 };

    sort(vec.begin(), vec.end()); 

    if (binary_search(vec.begin(), vec.end(), 16)) 
        std::cout << "16 was found in vec\n"; 
    else 
        std::cout << "16 was not found in vec\n" ; 

     if (binary_search(vec.begin(), vec.end(), 99)) 
        std::cout << "99 was found in vec\n"; 
    else 
        std::cout << "99 was found in vec\n"; 
}




/*
run:

16 was not found in vec
99 was found in vec

*/

 



answered Mar 5, 2023 by avibootz
...