binary_search() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). binary_search() is a method in the STL that tests if a certain value exists in sorted sequence.

Syntax:

binary_search( iterator_begin, iterator_end, val );
binary_search( iterator_begin, iterator_end, val, comparator );

Parameters: The binary_search() method accepts 4 parameters

  • iterator_begin: Iterator to the initial position
  • iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • val: Value to search
  • comparator: binary predicate which returns ​true if the first argument is less than the second.

Return value: True if val is found. False otherwise

Example of binary_search() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;


int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    v.push_back(6);

    if(binary_search(v.begin(), v.end(), 4))
        cout<<"4 is found! \n";

    if(!binary_search(v.begin(), v.end(), 7))
        cout<<"7 not found! \n";
}

Output:

4 is found!
7 not found! 

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top