O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.1. Iterating Through a Container

Problem

You have a range of iterators—most likely from a standard container—and the standard algorithms don't fit your needs, so you need to iterate through them.

Solution

Use an iterator or a const_iterator to access and advance through each of the elements in your container. In the standard library, algorithms and containers communicate using iterators, and one of the very ideas of the standard algorithms is that they insulate you from having to use iterators directly unless you are writing your own algorithm. Even so, you should understand the different kinds of iterators so you can use the standard algorithms and containers effectively. Example 7-1 presents some straightforward uses of iterators.

Example 7-1. Using iterators with containers

#include <iostream> #include <list> #include <algorithm> #include <string> using namespace std; static const int ARRAY_SIZE = 5; template<typename T, typename FwdIter> FwdIter fixOutliersUBound(FwdIter p1, FwdIter p2, const T& oldVal, const T& newVal) { for ( ;p1 != p2; ++p1) { if (greater<T>(*p1, oldVal)) { *p1 = newVal; } } } int main() { list<string> lstStr; lstStr.push_back("Please"); lstStr.push_back("leave"); lstStr.push_back("a"); lstStr.push_back("message"); // Create an iterator for stepping through the list for (list<string>::iterator p = lstStr.begin(); p != lstStr.end(); ++p) { cout << *p << endl; } // Or I can use a reverse_iterator to go from the end // to the beginning. rbegin returns a reverse_iterator ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required