Foreach in c++

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

Tags: , , , ,


5 Responses to “Foreach in c++”

  1. I’m sure this is nice, but I wanted to point out that boost also can do foreach.

  2. KungPhoo says:

    The typeof operator is quite a new C++ feature.
    Would this work? :
    for(k.iterator it=k.begin(); it!=k.end(); ++it)

  3. Doches says:

    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…

Leave a Reply

You must be logged in to post a comment.

[cache: storing page]