Search code examples
c++for-loopiterationstdvector

c++ best way to use for loop


I have this question that runs in my mind... I have a std::vector to iterate: which is the best way (the faster) to iterate?

here is the code using an iterator:

// using the iterator
for( std::vector <myClass*>::iterator it = myObject.begin( ); it != myObject.end( ); it++ )
{
    (*it)->someFunction( );
}

and here is 'normal' mode...

// normal loop
for( int i = 0; i < myObject.Size( ); i++ )
{
    myObject[i]->someFunction( );
}

thanks for your suggestions!


Solution

  • None of the two will be any faster really, because on most implementations a vector<T>::iterator is just a typedef for T* and size is cached.

    But doing ++it instead of it++ is a good habit. The latter involves creating a temporary.

    for(std::vector <myClass*>::iterator it = myObject.begin( );
                               it != myObject.end( );
                               ++it)
                               ^^^^  
    

    On other containers such as map, list etc. with nontrivial iterators the difference between postincrement and preincrement might become noticable.