Game Development Reference
In-Depth Information
Listing 13-8. string::reverse_iterator
for (string::reverse_iterator iter = myString.rbegin(); iter != myString.rend(); ++iter)
{
cout << *iter << endl;
}
The reverse_iterator is used with the methods rbegin and rend . Listing 13-9 shows the const
versions of the iterators.
Listing 13-9. Const Iterators
for (string::const_iterator iter = myString.cbegin(); iter != myString.cend(); ++iter)
{
cout << *iter << endl;
}
for (string::const_reverse_iterator iter = myString.crbegin();
iter != myString.crend();
++iter)
{
cout << *iter << endl;
}
Constant iterators are different from normal iterators in that you cannot modify the data to which they
are pointing. Listing 13-10 shows how you could have modified the data pointed to by an iterator.
Listing 13-10. Using Iterators to Alter Data
for (string::iterator iter = myString.begin(); iter != myString.end(); ++iter)
{
*iter = 'a';
cout << *iter << endl;
}
This simple example shows how you can modify data through an iterator dereference. Trying to
assign through a const_iterator would result in a compile error. If your loops are designed to only
read from your collection using an iterator you should prefer a const_iterator to ensure that no
mistakes are made that can alter your data.
There is also a more modern way of looping over all of the elements in an STL collection, the
range-based for loop. You can use a range-based for loop with any C++ type that has a begin and
end method; this includes classes that you write yourself. Listing 13-11 shows a range-based for
loop with our string.
Listing 13-11. Range-Based for
for (char &letter : myString)
{
cout << letter << endl;
}
 
Search WWH ::




Custom Search