moala moala - 1 year ago 70
C++ Question

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++)
// ...


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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download