std::binary_search() in C++ STL
Last Updated :
23 Jul, 2025
In C++, STL provide std::binary_search() function which implements binary search algorithm to check whether an element exists in the given sorted range. It is defined inside <algorithm> header file. In this article, we will learn about std::binary_search() function in C++.
Example:
C++
// C++ Program to illustrate the use of
// std::binary_search() method
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 6, 8, 9};
int k = 8;
if (binary_search(v.begin(), v.end(), k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
binary_search() Syntax
std::binary_search(first, last, k, comp);
Parameters
- first: Iterator to the first element of the range.
- last: Iterator to the theoretical element just after the last element of range.
- k: The value to be search.
- comp: Custom comparator. By default, it returns true if k is equal to the current element in the range.
Return Value
- Returns true, if k is present in the given range.
- Returns false, if k is not present in the given range.
Note: Behaviour of binary_search() is undefined if the given range is not sorted as binary search algorithm can only be implemented on sorted data.
More Examples of binary_search()
The following examples demonstrates the different use cases of std::binary_seach() function:
Example 1: Checking if an Element Exists in Array using std::binary_search()
C++
// C++ Program to check if an element exists in
// in an array using std::binary_search()
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[] = {1, 4, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 7;
// Check if the element exists
if (binary_search(arr, arr + n, k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
Example 2: Using binary_search() on a Set Container
C++
// C++ Program to check if an element exists in
// in an set using std::binary_search()
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 4, 5, 7, 9};
int k = 8;
// Check if the element exists
if (binary_search(s.begin(), s.end(), k))
cout << k << " is Present";
else
cout << k << " is NOT Present";
return 0;
}
Explanation: Even though set container does not have random access, binary_search() function still works because of the reason discussed below.
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems