#define for_all_impl(var, cont, mode) for (auto var##_begin_it = cont.##mode##begin(), var##_end_it = cont.##mode##end(), var##_it = var##_begin_it; var##_it != var##_end_it; ++var##_it) if (bool b = true) for (auto& var(*var##_it); b; b = false, var) if (bool b = true) for (const auto var##_num(var##_it - var##_begin_it); b; b = false, var##_num)
#define for_all(var, cont) for_all_impl(var, cont, )
#define for_all_const(var, cont) for_all_impl(var, cont, c)
#define for_all_reverse(var, cont) for_all_impl(var, cont, r)
#define for_all_const_reverse(var, cont) for_all_impl(var, cont, cr)
int main()
{
std::vector<int> a; a.push_back(0); a.push_back(1); a.push_back(2); a.push_back(3);
for_all(i, a)
{
std::cout << i_num << ": " << i << std::endl;
}
}
The reason I made it is because for a long time C++ had no easy shortcut to iterate through a data structure without lots of typing. Now we have the new range-based for loop syntax, but that has no easy way to give you the current index or go backwards (that I know of).
I spent a lot of time designing it so please give it the benefit of the doubt, and point out any big flaws. I have made the assumption only regular variable names will be used as parameters. I'm not putting it forward for everyone but I will use it in my project from now on unless it has a big problem.
Thanks.
Edit: I realise the index counter (i_num) won't work for all data structures such as lists. But I still think it's handy.