Range Based for Loops: Introduction

Motivation

for looping over containers is very loud …

  • Iterators are cumbersome

  • … albeit necessary

  • for_each not always applicable

  • ⟶ Why not building it into the language itself?

Iteration, the cumbersome way

std::vector<int> v{1,2,3};
for (std::vector<int>::const_iterator it=v.begin();
     it!=v.end();
     ++it)
  std::cout << *it << std::endl;

This is cumbersome indeed …

  • typedef does not exactly help

  • Iterators dereferenced by hand

  • ⟶ Much too loud!

Enter Range Based for Loops

Solution: coupling the language with its standard library

std::vector<int> v{1,2,3};
for (int i: v)
    std::cout << i << std::endl;

Note

Almost like Python, isn’t it?

Range Based for Loops, And auto

  • Works with the usual auto incarnations …

  • Valid for all C++ container types, arrays, initializer lists, etc.

auto Variants
std::vector<int> v{1,2,3};
for (auto& i: v) i = -i;
for (const auto& i: v)
    std::cout << i << std::endl;

Case Study: std::map Iteration

See Case Study: Range Based for On std::map