C++0x highlights #0: Range Based For Loop


Herb Sutter has some good news, C++0x looks like it could end up as C++11! This is going to be a great update to the C++ language. Lots of advanced features, like closures, a new memory model, portable threading support etc., are coming, but I think the one that I miss most often is the really simple Range Based For Loop (especially combined with Type Inference).

The following for loop:

map<SomeClass, vector> someclass_strings_map;
for (map<SomeClass, vector>::const_iterator it = someclass_strings_map.begin();
    it != someclass_strings_map.end(); ++it) {
    do_something_with(it->second);
}

is one of the reasons the Python, Ruby (and Java since 1.5) people laugh at us. But next year, we will be able to do:

for (auto x : foo_strings_map) {
        do_something_with(x.second);
}

PS: while I was compiling this example, I remembered another tiny improvement, you can now do map<Foo, vector<string>>. Notice the missing space? C++ no longer confuses nested templates with the shift/stream operator. Currently, you need an extra space: map<Foo, vector<string> >

PPS: If do_something_with() is a simple function this could be done with a for_each and a lambda/closure, but that is another story.

If you enjoyed this post, you can subscribe to my blog, or follow me on Twitter.

2 Responses to “C++0x highlights #0: Range Based For Loop”

  1. Mike Davis Says:

    is x.second() a typo with respect to the ‘()’ in the second example?

    Thanks,


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 324 other followers

%d bloggers like this: