7.1. Iterating Through a Container


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.


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 ...

Get C++ Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.