Posts Tagged ‘goodies’

Foreach in c++

Posted by
Thursday, October 28th, 2010 10:58 pm

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 :)

[cache: storing page]