I have a vector of objects and am iterating through it using a range-for loop. I am using it to print a function from the object, like this:
vector
I created a preprocessor macro (greatly simplified by @Artyer) that handles this for you in a relatively clean way:
#define for_indexed(...) for_indexed_v(i, __VA_ARGS__)
#define for_indexed_v(v, ...) if (std::size_t v = -1) for (__VA_ARGS__) if ((++v, true))
Example usage:
std::vector v{1, 2, 3};
for_indexed (auto const& item : v) {
if (i > 0) std::cout << ", ";
std::cout << i << ": " << item;
}
To use a different loop variable:
for_indexed_v (my_counter, auto const& item : v) ...
The extra control flow logic should be optimized away in any non-debug builds. You're left with a relatively easy-to-read loop syntax.
2020 note: It would probably be more wise to use a lambda-based solution instead of macro trickery. Of course, the syntax wouldn't be as "clean", but it would have the advantage of being recognizable as actual C++ syntax. The choice is yours.
Update 2017/05/28: Made break; statements work correctly
Update 2019/01/28: Put for in the macro name so that the word indexed is a valid variable name. I doubt for_indexed will cause any conflicts.
Update 2020/12/23: Simplified drastically (thanks @Artyer)