Iterators
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.
1 // Fig. 18.10: Fig18_10.cpp 2 // Using an iterator to output a string. 3 #include 4 using std::cout; 5 using std::endl; 6 7 #include 8 using std::string; 9 10 int main() 11 { 12 string string1( "Testing iterators" ); 13 string::const_iterator iterator1 = string1.begin(); 14 15 cout << "string1 = " << string1 16 << " (Using iterator iterator1) string1 is: "; 17 18 // iterate through string 19 while ( iterator1 != string1.end() ) 20 { 21 cout << *iterator1; // dereference iterator to get char 22 iterator1++; // advance iterator to next char 23 } // end while 24 25 cout << endl; 26 return 0; 27 } // end main
|
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
Use string member function at (rather than iterators) when you want the benefit of range checking. |
Good Programming Practice 18.2
When the operations involving the iterator should not modify the data being processed, use a const_iterator. This is another example of employing the principle of least privilege. |