C++ STL Binary Search

  1. C++ STL binary_search() Overview
  2. C++ Program for Binary Search
Note

If you want to understand Binary Search in detail, then refer to the binary search algorithm article.

C++ provides us with a ready-to-use function binary_search() so that we don’t have to implement the function ourselves. It is a very simple to use and efficiently implemented method and not prone to errors.

C++ STL binary_search() Overview

Syntax

DEFAULT:       
template <class ForwardIterator, class T>  
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val);  
  
CUSTOM COMPARISON FUNCTION:     
template <class ForwardIterator, class T, class Compare>  
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);  

Here, T can be any of the following: int, float, short, long, byte, char, double, and even a user-defined Object as well.

It checks whether an element inside [first, last) matches the target element X using the binary search algorithm. By default, it uses the less-than operator to compare elements, but we can also provide our own custom comp as described in the second template given above.

Parameters

first A forward iterator pointing towards the first element in the given array range.
last A forward iterator pointing towards the last element in the given array range.
comp A user-defined binary predicate function that accepts two forward iterators as arguments and returns true if the two arguments are present in the correct order. It does not modify any arguments and follows the strict weak ordering to order the elements.
val The target element we are searching inside the given array range.

Return

If it finds the target element, then it returns true; else it returns false.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> v = {1, 2, 3, 4, 5, 6};

    if (binary_search(v.begin(), v.end(), 5)) {
        cout << "Element found" << endl;
    }
    else {
        cout << "Element not found" << endl;
    }

    return 0;
}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.