TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

 Home » Tip Bank » Visual Basic » Windows
Language: C++
Expertise: Intermediate
Jun 12, 2000

WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <algorithm> 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 <algorithm>
#include <vector>
using namespace std;
int main()
{
int arr[5] = {1,3,4,5,5};
// set a vector from the array
vector <int> 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
}
``````
Danny Kalev

 Submit a Tip Browse "Visual Basic" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date