From the course: C++ Templates and the STL

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Binary searches

Binary searches

- [Instructor] The binary search function performs a classic binary search on a sorted container. Here I have a working copy of binsearch.cpp from chapter six of the exercise files. You'll notice I have a reverse comparison operator here, a greater than comparison, which we'll use a little bit later. Here I have a vector of prime numbers that are not sorted. So we start by sorting the vector and then we can search for a number, and in this case, we're searching for n, which is 47. So when I build and run, you notice that first it sorts the container and it finds 47, of course, 'cause that's one of our prime numbers. If I change this to 48, and build and run, you'll notice that it is not found. So binary search returns a Boolean value, it's true if it's found and it's false if it's not found. So I'm going to return our 48 to a 47 and see what else we can do. Of course, we can use our custom comparison operator that will sort it in reverse order. So I can say greater than comp, int, and…

Contents