Quick Q: Can I do something like range-for with a counting loop?

Quick A: Yes. Start with boost::irange.

Recently on SO:

Can I do something like range-for with a counting loop?

Actually this are two related questions.

I know there is new syntax in C++11 for range based for loops of the form:

//v is some container
for(auto &i: v){
   // do something with i
}

First question: how can I infer at which iteration I am in this loop? (Say I want to fill a vector with value j at position j).

Second question: I wanted to now if there also is some other way to write a loop of the form

for(int i=0; i<100; i++){ ... }

I find this way of writing it a bit cumbersome and I do this so often and I would love to have a more concise syntax for it. Something along the lines:

for(i in [0..99]){ ... }

would be great.

For both questions I would like to avoid having to use additional libraries.

Add a Comment

Comments are closed.

Comments (1)

0 0

jbruni said on Apr 17, 2015 11:19 AM:

Related to this question is my desire to iterate over the values of an enumeration.

If there was a compile-time operator that would convert an enumeration to a std::initializer_list literal, then my request would be satisfied. I think converting your [0..99] syntax to a std::initializer_list literal would also work.