Why use string::iterator rather than index? [duplicate]
Solution 1:
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.
Solution 2:
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"
.
Solution 3:
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
Solution 4:
Duplicate of:
- Iterators.. why use them?
- Why use iterators instead of array indices?
That said, it's a matter of genericity. You can do a lot more with iterators using STL than with array access. Also, if you need to refactor code, and change the string to a vector, list or rope, you wont have to rewrite your code at all.
Finally there's the question of safety in iteration. If you want to access the NEXT character in your loop, with iterators you could do that safely, but increasing the array subscript might segfault on you on the last element, hence needing another check.