Saturday, March 15, 2008

C++ foreach

I can never remember the C++ for-each loop syntax. Thus, a helper macro I use:
    #define for_each(type, it, L) for (type::iterator (it) = (L).begin(); (it) != (L).end(); ++(it))
If L has type T, usage is:
    for_each(T, it, L) {
    printf("%d\n", (*it));
    }
If you're only using gcc, one can use __typeof__ [1] to simplify this.