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.
Depending on the actual container, incrementing an iterator might be faster than indexing (think linked lists).
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
An index (or key) is used to look up data in a container. The simplest case would be the integer indexes of an array, but containers like std::map can have nearly any type as an index. An iterator is a class which represents a position in a container.
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.
Iterators are a standard interface. By using iterators, you can use the same algorithms with different containers. The final decision whether to use them or not is up to you based on usability and readability.
For example, using the standard transform algorithm to covert std::string
to uppercase:
std::string str = "A String";
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
will result in str
being equal to "A STRING"
.
For std::string specifically, i would suggest you use indexes since it supports Random Access and its simpler that way. The only reason its "recommended" to use iterators is because iterators offer a standard interface to access sequences so that if your sequence changed to std::list for example, your iteration code would remain un-affected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With