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 main advantage is that iterator code works for all stl containers, while the array indexing operator [] is only available for vectors and deques. This means you are free to change the underlying container if you need to without having to recode every loop.
Depending on the actual container, incrementing an iterator might be faster than indexing (think linked lists).
An index (or key) is used to look up data in a container. The simplest case would be the integer indexes of an array, but containers like std::map can have nearly any type as an index. An iterator is a class which represents a position in a container.
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.
I presume you are talking about when using a vector, right?
The main advantage is that iterator code works for all stl containers, while the array indexing operator []
is only available for vectors and deques. This means you are free to change the underlying container if you need to without having to recode every loop. It also means you can put your iteration code in a template and it will work for any container, not just for deques and vectors (and arrays of course).
All of the standard containers provide the iterator concept. An iterator knows how to find the next element in the container, especially when the underlying structure isn't array-like. Array-style operator[]
isn't provided by every container, so getting in the habit of using iterators will make more consistent-looking code, regardless of the container you choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With