Why use iterators instead of array indices?


Take the following two lines of code:

for (int i = 0; i < some_vector.size(); i++)
    //do stuff

And this:

for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
    //do stuff

I'm told that the second way is preferred. Why exactly is this?

10/21/2008 9:43:27 PM

Accepted Answer

The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in

T elem = some_vector[i];

then you're making the assumption that the container has operator[](std::size_t) defined. Again, this is true for vector but not for other containers.

The use of iterators bring you closer to container independence. You're not making assumptions about random-access ability or fast size() operation, only that the container has iterator capabilities.

You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use std::for_each(), std::transform() and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.

5/31/2011 3:13:07 PM

because you are not tying your code to the particular implementation of the some_vector list. if you use array indices, it has to be some form of array; if you use iterators you can use that code on any list implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow