Why use string::iterator rather than index?

Viewed 75074

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.

9 Answers

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

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.

In cases where you don't know which class you're iterating over (because it's a template argument), you should use an iterator because not every class that provides an iterator also provides [] (and not every class that does provide [], provides one which works in O(1) time). So by using iterator you'll make sure that the function will work with as many classes as possible (though not with C arrays).

In this specific case, I see no reason to prefer one over the other except personal preference or maybe premature optimization.

Both works.

The main reason would be consistency: you're iterating over a collection or the characters of a string the same way, by requesting an iterator and making it advance.

I would not say the implementation details of ++it resulting in a pointer increment compared to str[i] involving pointer arithmetics is worth mentioning. And range checking are implementation detail as well.

Iterators are safer and provide more flexibility as posted by someone else too.In additon an index only can be used for containers that (efficiently) support random access (i.e. direct access to an element at a given position).An iterator is a more general concept. Iterators offer efficient traversal of linked lists, files, and a number of other data structures. It often leads to the generation of more efficient code.

In C++, you can do many things in many different ways. This is one more example. In this case, there is no difference which method to use. But in general, iterators are faster, safer and provide more flexibility amond different types of containers.

Related