Search code examples
c++iteratorcontainers

Best way to iterate through a container


What are the Advantages/Drawbacks of these two ways of iterating through a container / which one do you prefer and why:

for (MyClass::iterator i = m.begin(), e = m.end() ; i != e ; i++)
{
    // ...
}

or

for (MyClass::iterator i = m.begin() ; i != m.end() ; i++)
{
    // ...
}

Subsidiary question: i++ or ++i? Why?


Solution

  • If the iterator is non-trivial (ie. not a pointer), ++i is definitely faster as it doesn't involves a copy to a temporary, which may or may not be optimized out.

    The first form is a little faster but could be wrong if you erase or insert things in the loop.

    For simple iteration over a container I use

    #define foreach BOOST_FOREACH // in some header
    
    foreach(MyType &element, any_container) {
      // deal with element
    }
    

    most of the time for succinctness and clarity.