std::binary_search() in C++ STL (original) (raw)
Last Updated : 20 Jan, 2026
std::binary_search() is a C++ STL algorithm used to efficiently check whether a specific value exists in a sorted range. It is defined in the header and works with arrays and STL containers such as vector and set.
C++ `
#include <bits/stdc++.h> using namespace std; int main() { vector 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;}
`
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 comparison function that defines the ordering of elements. By default, std::less is used.
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.
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++ `
#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;}
`
**Explanation: This program uses std::binary_search() to check whether the value 7 exists in a sorted integer array and prints whether it is present or not.
**Example 2: Using binary_search() on a Set Container
C++ `
#include <bits/stdc++.h> using namespace std;
int main() { set 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.