I just wanted to know what is the main advantage of using the iterators over the array indices. I have googled but i am not getting the right answer.
The STL contains algorithms, such as transform
and for_each
that operate on containers. They don't accept indices, but use iterators.
Iterators help hide the container implementation and allow the programmer to focus more on the algorithm. The for_each
function can be applied to anything that supports a forward iterator.
I would say it's more a matter of consistency and code reuse.
Finally, I'd like to say that even C
arrays have iterators.
const Foo* someArray = //...
const Foo* otherArray = new Foo[someArrayLength];
std::copy(someArray, someArray + someArrayLength, otherArray);
The iterator_traits
class has been specialized so that pointers or a model of RandomAccessIterator
.
One other slight difference is that you can't use erase() on an element in a vector by index, you must have an iterator. No big deal since you can always do "vect.begin() + index" as your iterator, but there are other considerations. For example, if you do this then you must always check your index against size() and not some variable you assigned that value.
None of that is really too much worth worrying about but if given the choice I prefer iterator access for the reasons already stated and this one.