Lecture overview -- Keyboard shortcut: 'u'  Previous page: Principles used for algorithms -- Keyboard shortcut: 'p'  Next page: Function objects -- Keyboard shortcut: 'n'  Lecture notes - all slides together  Annotated slide -- Keyboard shortcut: 't'  Alphabetic index  Help page about these notes  Course home    Templates and The Standard Library - slide 34 : 39

The for-each algorithm

In C++ for-each is an algorithm, not a control structure like foreach in C#

C++ 2011 has introduced a 'range based for loop' similar to foreach in C#

// The C++ Programming Language, 3ed, page 524.
// Possible definition of the for_each function template. 
template <class In, class Op> Op for_each(In first, In last, Op f){
  while (first != last) f(*first++);
  return f;
}
for-each-reproduction-1.cpp
Implementation and sample use of for-each on an C-style array.
for-each-reproduction-2.cpp
Implementation and sample use of for-each on a list of integers.