devxlogo

The binary_search Algorithm

STL’s binary_search() algorithm traverses a sequence and returns a Boolean value indicating whether the sought-after element exists in that sequence. binary_search() is declared in the header as follows:

 bool binary_search (ForwardIterator first,                     ForwardIterator last,                     const T& value)

binary_search() takes two forward iterators that mark the sequence’s bounds, and the sought-after value as the third argument. It returns true if the sought-after value exists in the sequence, or false otherwise. In the following example, binary_search() checks whether the integers 5 and 0 exist in a vector of integers:

 #include #include using namespace std;int main(){  int arr[5] = {1,3,4,5,5};  // set a vector from the array  vector  vi(arr, arr+5);  // search for 5 and 0 in the vector  bool found = binary_search(vi.begin(), vi.end(), 5);// true  found = binary_search(vi.begin(), vi.end(), 0);// false}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.