Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page