Range Based for Loops: Introduction#
Motivation#
for looping over containers is very loud …
Iterators are cumbersome
… albeit necessary
for_eachnot 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 …
typedefdoes not exactly helpIterators 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
autoincarnations …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;