C++0x step by step: range for

Range for is another of those syntactic sugar enhancements that enables you to do the same as before, but with less code. Often, you find yourself iterating through all elements of a container and doing something with those elements. In my original example, that was done by the following code:


for(auto i = data.begin(); i< data.end(); i++)
{
       cout << i->a << endl;
}


It is the traditional way to do this, but it means you’re declaring an iterator, getting the begin and end, and then ++ing from start to finish. With C++0x, you can write this in shorthand with the construct know as ‘range for’ which means what it says ‘Do this for the entire range’. It is very similar to the foreach keyword in C#.


for(auto &i: data)
{
       cout << i.a << endl;
}


As you can see, this is just a nicer way to do the same thing you did before.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>