
- The C Standard Library
- The C Standard Library
- The C++ Standard Library
- C++ Library - Home
- C++ Library - <fstream>
- C++ Library - <iomanip>
- C++ Library - <ios>
- C++ Library - <iosfwd>
- C++ Library - <iostream>
- C++ Library - <istream>
- C++ Library - <ostream>
- C++ Library - <sstream>
- C++ Library - <streambuf>
- C++ Library - <atomic>
- C++ Library - <complex>
- C++ Library - <exception>
- C++ Library - <functional>
- C++ Library - <limits>
- C++ Library - <locale>
- C++ Library - <memory>
- C++ Library - <new>
- C++ Library - <numeric>
- C++ Library - <regex>
- C++ Library - <stdexcept>
- C++ Library - <string>
- C++ Library - <thread>
- C++ Library - <tuple>
- C++ Library - <typeinfo>
- C++ Library - <utility>
- C++ Library - <valarray>
- The C++ STL Library
- C++ Library - <array>
- C++ Library - <bitset>
- C++ Library - <deque>
- C++ Library - <forward_list>
- C++ Library - <list>
- C++ Library - <map>
- C++ Library - <queue>
- C++ Library - <set>
- C++ Library - <stack>
- C++ Library - <unordered_map>
- C++ Library - <unordered_set>
- C++ Library - <vector>
- C++ Library - <algorithm>
- C++ Library - <iterator>
- C++ Programming Resources
- C++ Programming Tutorial
- C++ Useful Resources
- C++ Discussion
C++ Algorithm Library - binary_search() Function
Description
The C++ function std::algorithm::binary_search() tests whether value exists in sorted sequence or not. It use comp function for comparison.
Declaration
Following is the declaration for std::algorithm::binary_search() function form std::algorithm header.
C++98
template <class ForwardIterator, class T, class Compare> bool binary_search (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
Parameters
first − Forward iterators to the initial positions of the searched sequence.
last − Forward iterators to the final positions of the searched sequence.
val − Value to search for in the range.
comp − Binary function that accepts two arguments and returns a bool.
Return value
Returns true if value exists otherwise false.
Exceptions
Throws exception if either element comparison or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Time complexity
Logarithmic in the distance between first and last.
Example
The following example shows the usage of std::algorithm::binary_search() function.
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; bool comp(string s1, string s2) { return (s1 == s2); } int main(void) { vector<string> v = {"ONE", "Two", "Three"}; bool result; result = binary_search(v.begin(), v.end(), "one", comp); if (result == true) cout << "String \"one\" exist in vector." << endl; v[0] = "Ten"; return 0; }
Let us compile and run the above program, this will produce the following result −
String "one" exist in vector.