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.
Implementation and sample use of for-each on an C-style array.
Implementation 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