Monday, 8 October 2012

Range-based for loops in a C++/CX app

One of the new developments introduced in C++11 are range-based for loops. Range-based for loops are an extension of the for keyword, and provide an efficient way to write loops that iterate over a collection - STL containers, strings, and arrays are ready-made for range-based for loops. In addition, they have a more concise syntax than for loops and the std::for_each algorithm.

Here’s a simple example that totals the integer values stored in an array.

int numbers[5] = { 1, 77, 98, 22, 355 };
int total = 0;
 
for (auto number : numbers)
{
    total += number;
}

In order to enable range-based for loops for your user-defined types, you must add the following support:

  • A begin method that returns an iterator to the beginning of the structure.

  • An end method that returns an iterator to the end of the structure.

  • Support in the iterator for the operator*, operator!=, and operator++ methods.

For more information see Algorithms (Modern C++), and the Hilo project.

No comments:

Post a Comment