| algorithms/for-each-implementation/for-each-reproduction-1.cpp - Implementation and sample use of for-each on an C-style array. | Lecture 6 - slide 20 : 40 Program 1 |
// A reproduction of the for-each algorithm, and a sample use on a C-style array.
#include <iostream>
#include <string>
// A possible definition of the for_each function template.
template <typename InputIt, typename Function>
Function for_each(InputIt first, InputIt last, Function f){
while (first != last) f(*first++); // Notice the use of operator() on f
return f;
}
void print_element(const int &i){
std::cout << i << std::endl;
}
int main(){
int a[] = {7,9,8,1,-1};
// The two first parameters are iterators:
for_each(a, a+3, print_element); // 7, 9, 8
std::cout << std::endl;
// Same with a lambda expression.
for_each(a, a+3, [](const int &el){std::cout << el << std::endl;}); // 7, 9, 8
}