Class string provides iterators for forward and backward traversal of strings. Iterators provide access to individual characters with syntax that is similar to pointer operations. Iterators are not range checked. Note that in this section we provide "mechanical examples" to demonstrate the use of iterators. We discuss more robust uses of iterators in Chapter 23. Figure 18.10 demonstrates iterators.
Figure 18.10. Using an iterator to output a string.
Lines 1213 declare string string1 and string::const_iterator iterator1. A const_iterator is an iterator that cannot modify the stringin this case the stringtHRough which it is iterating. Iterator iterator1 is initialized to the beginning of string1 with the string class member function begin. Two versions of begin existone that returns an iterator for iterating through a non-const string and a const version that returns a const_iterator for iterating through a const string. Line 15 outputs string1.
Lines 1923 use iterator iterator1 to "walk through" string1. Class string member function end returns an iterator (or a const_iterator) for the position past the last element of string1. Each element is printed by dereferencing the iterator much as you would dereference a pointer, and the iterator is advanced one position using operator ++.
Class string provides member functions rend and rbegin for accessing individual string characters in reverse from the end of a string toward the beginning. Member functions rend and rbegin can return reverse_iterators and const_reverse_iterators (based on whether the string is non-const or const). In the exercises, we ask the reader to write a program that demonstrates these capabilities. We will use iterators and reverse iterators more in Chapter 23.
Error-Prevention Tip 18.1
Good Programming Practice 18.2