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.

Searching and counting

Searching and counting - C++ Tutorial

From the course: C++ Templates and the STL

Searching and counting

- [Instructor] The STL provides a number of algorithms for searching and counting elements in a sequence. Here I have a working copy of search.cpp from chapter six of the exercise files. Notice here that the vector I'm using is const-qualified. All of these functions are constant safe as they don't change the values of anything in the sequence in the container. We'll start here with the find function. The find function does a sequential search, using the equal to comparison. If the compared value is found it returns an iterator pointing to that value and if the value is not found, it returns the end point iterator. So I can test here for the end point iterator and if it's not at the end then I know that I found the element and when I build and run, it finds the number 41 at index 12. You notice I'm getting index 12 by subtracting the beginning from the iterator. The find_if function uses a unary operator and you'll notice that I have one up here, is_odd. Checks to see if what we're…

Contents