19.11. Iterators

Class string provides iterators (introduced in Chapter 15) for forward and backward traversal of strings. Iterators provide access to individual characters with a syntax that’s similar to pointer operations. Iterators are not range checked. Figure 19.10 demonstrates iterators.


 1   // Fig. 19.10: Fig19_10.cpp
 2   // Using an iterator to output a string.
 3   #include <iostream>
 4   #include <string>
 5   using namespace std;
 6
 7   int main()
 8   {
 9      string string1( "Testing iterators" );
10      string::const_iterator iterator1 = string1.begin();
11
12      cout << "string1 = " << string1
13         << " (Using iterator iterator1) string1 is: ";
14
15      // iterate through string                                 
16      while ( iterator1 != string1.end() )                      
17      {                                                         
18         cout << *iterator1; // dereference iterator to get char
19         ++iterator1; // advance iterator to next char          
20      } // end while                                            
21
22      cout << endl;
23   } // end main


string1 = Testing iterators
(Using iterator iterator1) string1 is: Testing iterators


Fig. 19.10. Using an iterator to output a string.

Lines 9–10 declare string string1 and string::const_iterator iterator1. Recall that a const_iterator cannot be used to modify the data that you’re iterating through—in this case the string. Iterator iterator1 is initialized to the beginning of string1 with the string class member function begin. Two versions of begin exist—one 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 12 outputs string1.

Lines 16–20 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’d dereference a pointer, and the iterator is advanced one position using operator ++. In C++11, lines 10 and 16–20 can be replaced with a range-based for, as in

for ( char c : string1 )
   cout << c;

Image

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 return reverse_iterators or const_reverse_iterators (based on whether the string is non-const or const).


Image Good Programming Practice 19.1

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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.175.243