Shorthand for for-loop - syntactic sugar in C++(11)

dingalapadum picture dingalapadum · Apr 8, 2015 · Viewed 29.6k times · Source

Actually these are two related questions.

I know there is a 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 know 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.

Answer

Mike Seymour picture Mike Seymour · Apr 8, 2015

First answer: you don't. You've used a simple construct for a simple purpose; you'll need something more complicated if you have more complicated needs.

Second answer: You could make an iterator type that yields consecutive integer values, and a "container" type that gives a range of those. Unless you have a good reason to do it yourself, Boost has such a thing:

#include <boost/range/irange.hpp>

for (int i : boost::irange(0,100)) {
    // i goes from 0 to 99 inclusive
}