Foreach in c++

Hi

I created simple helper that might help few of you who use c++ with STL. It adds foreach to the c++ that traverses over all of the STL container, so the code is more readable, like in this example:

#include <cstdio>
#include <vector>
#include "foreach.h"

 
int main()
{
    // make int vector and fill it
    vector<int> k;
    for (int i=0; i<10; ++i) k.push_back(i);

 
    // show what the upper loop filled
    foreach_ (it, k) printf("%i ",(*it));
    printf("\n");

 
    // show all the data, but get rid of 4
    // http://en.wikipedia.org/wiki/Tetraphobia :)
    foreachdel_ (it, k)
    {
        if (*it == 4) it=k.erase(it);
        printf("%i ",(*it));
    }
    printf("\n");

 
    return 0;
}

Will result in following:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 5 6 7 8 9

More on my blog:  http://pleasanthacking.com/2010/06/17/foreach-in-cpp/

I hope some of you will find it useful during compos :)

Tags: C++, goodies, libraries, libs, tools

Comments

29. Oct 2010 · 06:58 UTC
The typeof operator is quite a new C++ feature.

Would this work? :

for(k.iterator it=k.begin(); it!=k.end(); ++it)
30. Oct 2010 · 01:16 UTC
Not only would it work, but it’d be the appropriate C++/STL way of iterating over a collection. Though I’m sure rooks’ foreach_ method is nothing more than a macro that expands to exactly that…