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 - C++ Tutorial
From the course: C++ Templates and the STL
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
-
-
-
(Locked)
About STL algorithms1m 42s
-
(Locked)
Testing conditions2m 36s
-
(Locked)
Searching and counting4m 38s
-
(Locked)
Replacing and removing4m 14s
-
(Locked)
Modifying algorithms5m 46s
-
(Locked)
Partitions2m 52s
-
(Locked)
Sorting3m 42s
-
(Locked)
Merging sequences2m 4s
-
(Locked)
Binary searches3m 57s
-
(Locked)
-