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 <algorithm> header and returns true if the value is found.
- It can be used with arrays, vectors, sets, and other containers with suitable iterators.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 3, 6, 8, 9};
int k = 8;
if (std::binary_search(v.begin(), v.end(), k))
std::cout << k << " is Present";
else
std::cout << k << " is NOT Present";
return 0;
}
Output
8 is Present
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<T> 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: Checking if an Element Exists in Array
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 4, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 7;
if (std::binary_search(arr, arr + n, k))
std::cout << k << " is Present";
else
std::cout << k << " is NOT Present";
return 0;
}
Output
7 is Present
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: Using binary_search() with a Set
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::set<int> s = {1, 4, 5, 7, 9};
int k = 8;
if (std::binary_search(s.begin(), s.end(), k))
std::cout << k << " is Present";
else
std::cout << k << " is NOT Present";
return 0;
}
Output
8 is NOT Present
Explanation: std::binary_search() can work with a std::set because its iterators can be traversed to perform the required comparisons. However, it does not take advantage of the set's tree structure and may require linear iterator movement.