C++ examples for STL Algorithm:binary_search
Search element in a sequence with algorithm binary_search.
#include <iostream> #include <algorithm> // algorithm definitions #include <vector> // vector class-template definition #include <iterator> using namespace std; int main() /*from w w w. ja va2s . co m*/ { const int SIZE = 10; int a[ SIZE ] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; vector< int > v( a, a + SIZE ); // copy of a ostream_iterator< int > output( cout, " " ); cout << "Vector v contains: "; copy( v.begin(), v.end(), output ); // display output vector // sort elements of v sort( v.begin(), v.end() ); // use binary_search to locate 13 in v if ( binary_search( v.begin(), v.end(), 13 ) ) cout << "\n\n13 was found in v"; else cout << "\n\n13 was not found in v" ; // use binary_search to locate 100 in v if ( binary_search( v.begin(), v.end(), 100 ) ) cout << "\n100 was found in v" ; else cout << "\n100 was not found in v" ; cout << endl; }