std::vector iterator or index access speed question

Posted by Simone Margaritelli on Stack Overflow See other posts from Stack Overflow or by Simone Margaritelli
Published on 2010-03-26T15:06:40Z Indexed on 2010/03/26 15:13 UTC
Read the original article Hit count: 377

Filed under:
|
|
|
|

Just a stupid question .

I have a

std::vector<SomeClass *> v;

in my code and i need to access its elements very often in the program, looping them forward and backward .

Which is the fastest access type between those two ?

Iterator access

std::vector<SomeClass *> v;
std::vector<SomeClass *>::iterator i;
std::vector<SomeClass *>::reverse_iterator j;

// i loops forward, j loops backward
for( i = v.begin(), j = v.rbegin(); i != v.end() && j != v.rend(); i++, j++ ){
    // some operations on v items
}

Subscript access (by index)

std::vector<SomeClass *> v;
unsigned int i, j, size = v.size();

// i loops forward, j loops backward
for( i = 0, j = size - 1; i < size && j >= 0; i++, j-- ){
    // some operations on v items
}

And, does const_iterator offer a faster way to access vector elements in case i do not have to modify them?

Thank you in advantage.

© Stack Overflow or respective owner

Related posts about c++

Related posts about vector