The One True Iterator Declaration

The One True Iterator Declaration

Continueing my rich history of bikeshed-quality blog posts, I proudly present:

Three common ways to declare the iterators for iterating over a map:

  1. for ( map<string, string>::const_iterator it = map.begin(); it != map.end(); ++it );
    Not bad. Unfortunately the line is kinda long, and the .end() function is queried over and over again. On the plus side, the iterator is nicely scoped (only valid within the loop) – but that doesn’t work with MSVC6. Oh well.

  2. map<string, string>::const_iterator it = map.begin();
    map<string, string>::const_iterator end = map.end();
    for ( ; it != end; ++it );

    Not so cool. Both ‘it’ and ‘end’ outside of the scope of the loop. Might be what you want (for instance, the loop could break as soon as it (no pun intended) found a match. The super-sort for() line looks nice, and there are no unnecessary calls to map.end().

  3. map<string, string>::const_iterator it, end = map.end();
    for ( it = map.begin(); it != end; ++it );

    My personal style. The lines are both pretty short – in particular, I don’t have to type the silly map::const_iterator string twice. map.end() is queried only once.The only thing which bothers me (a little bit) is that ‘it’ and ‘end’ are valid outside of the loop, which is usually not what I want. I usually put the whole thing into { } to fix that.

How do you do it? 🙂