Hassen Dhia Hassen Dhia - 6 months ago 21
C++ Question

Does the operator [] of std::vector<type> walk through the vector from the beginning on each call

I see many programmers using

to access the vector's elements in a
loop this way :

for (int c=0;c<vect.size();c++)
vect[c] ....

but when i use ieterators i get a better performance can you explain why ?

for (std::vector<type>::iterator it = vect.begin();it<vect.end();it++)
*it = ...

a possible reason that can be wrong it that the operator
works like in the case of a linked list , it is navigating through the vector till reaching the element of the desired index


The access time in vector with the [] operator is constant.

That means it is not working its way through any kind of list.
There is no need at all, vector is implemented as a malloced array; all vector adds to it is the automatic resizing, which just means that it makes another malloc and copies the content for you, without introducing errors. You can see that yourself by open the include <vector>.