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 and notes together  slide -- Keyboard shortcut: 't'  Help page about these notes  Alphabetic index  Course home  Lecture 5 - Page 34 : 39
Notes about C++
Templates and The Standard Library
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;
}

A possible implementation of the for-each algorithm.

y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/algorithms/for-each-implementation/for-each-reproduction-1.cppImplementation and sample use of for-each on an C-style array.


y:/Kurt/Files/Advanced-programming-cpp/cpp/kn/algorithms/for-each-implementation/for-each-reproduction-2.cppImplementation and sample use of for-each on a list of integers.


  • A Stroustrup advice:

    • "In general, before using for_each(), consider if there is a more specialized algorithm that would do more for you"

      • Such as find() or accumulate()

  • Observation about the return-value of for_each

    • The function f of type Op is returned.

      • Later we will see an example where this is convenient