Why use string::iterator rather than index?

71,606

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:

  1. Iterators.. why use them?
  2. 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.

Solution 5

As stated in this question, size() method is not guaranteed to be O(1)

Share:
71,606
Jichao
Author by

Jichao

Full stack hello world developer

Updated on November 17, 2020

Comments

  • Jichao
    Jichao over 3 years

    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.