A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/cpp_standard_library/cpp_algorithm_binary_search_default.htm below:

C++ Algorithm Library - binary_search() Function

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 operator< for comparison.

Declaration

Following is the declaration for std::algorithm::binary_search() function form std::algorithm header.

C++98
template <class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
Parameters 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>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};
   bool result;

   result = binary_search(v.begin(), v.end(), 3);

   if (result == true)
      cout << "Element 3 exist in vector." << endl;

   v[2] = 10;

   result = binary_search(v.begin(), v.end(), 3);

   if (result == false)
      cout << "Element 3 doesn't exist in vector." << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Element 3 exist in vector.
Element 3 doesn't exist in vector.

algorithm.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4