0
0
CppHow-ToBeginner · 3 min read

How to Use binary_search in C++: Syntax and Example

In C++, use std::binary_search from the <algorithm> header to check if an element exists in a sorted container. It returns true if the element is found and false otherwise. Ensure the container is sorted before calling binary_search for correct results.
📐

Syntax

The std::binary_search function has two main forms:

  • std::binary_search(begin, end, value): Searches for value in the sorted range [begin, end).
  • std::binary_search(begin, end, value, comp): Uses a custom comparison function comp for searching.

Parameters:

  • begin, end: Iterators defining the sorted range to search.
  • value: The element to find.
  • comp: Optional comparison function (like std::less<T>).

Returns true if value is found, otherwise false.

cpp
template<class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value);

template<class ForwardIt, class T, class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value, Compare comp);
💻

Example

This example shows how to use std::binary_search to check if a number exists in a sorted vector.

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

int main() {
    std::vector<int> numbers = {1, 3, 5, 7, 9};
    int target = 5;

    // The vector must be sorted for binary_search to work correctly
    bool found = std::binary_search(numbers.begin(), numbers.end(), target);

    if (found) {
        std::cout << target << " is in the list.\n";
    } else {
        std::cout << target << " is NOT in the list.\n";
    }

    return 0;
}
Output
5 is in the list.
⚠️

Common Pitfalls

Common mistakes when using std::binary_search include:

  • Using it on an unsorted container, which leads to incorrect results.
  • Confusing binary_search with functions that return the element's position; binary_search only returns true or false.
  • Not using the same comparison function for sorting and searching when using a custom comparator.

Example of wrong and right usage:

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

int main() {
    std::vector<int> unsorted = {3, 1, 4, 2};
    int target = 3;

    // Wrong: binary_search on unsorted vector
    bool found_wrong = std::binary_search(unsorted.begin(), unsorted.end(), target);

    // Sort before searching
    std::sort(unsorted.begin(), unsorted.end());
    bool found_right = std::binary_search(unsorted.begin(), unsorted.end(), target);

    std::cout << "Found without sorting: " << (found_wrong ? "Yes" : "No") << "\n";
    std::cout << "Found after sorting: " << (found_right ? "Yes" : "No") << "\n";

    return 0;
}
Output
Found without sorting: No Found after sorting: Yes
📊

Quick Reference

Tips for using std::binary_search:

  • Always ensure the container is sorted before calling binary_search.
  • binary_search returns a boolean, not the element's position.
  • Use the same comparison logic for sorting and searching.
  • Works with any container supporting random access or forward iterators.

Key Takeaways

Use std::binary_search on sorted containers to check if an element exists.
binary_search returns true or false, not the element's index.
Always sort your container before using binary_search to get correct results.
Use the same comparison function for sorting and searching if you use a custom comparator.