Possible Duplicate:
Why use iterators instead of array indices?
string::iterator it;
for (it = str.begin(); it < str.end(); it++)
cout << *it;
cout << endl;
Why not:
for (int i = 0; i < str.size(); i++)
cout << str[i];
cout << endl;
It seems that string::iterator does not provide range check either. Why should we use string::iterator rather than index?
Thanks.
The index can only be used for containers that support random access – direct access to a given position.
The iterator offers a unified way to access any collection/data structure. The flexibility when refactoring your code is immense.