Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          algorithms/for-each-implementation/for-each-reproduction-2.cpp - Implementation and sample use of for-each on a list of integers.Lecture 6 - slide 20 : 40
Program 2

// Same defintion of for-each. Use of the algorithm on a list of integers: list<int>.

#include <iostream>
#include <string>
#include <list>

// 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++);
  return f;
}

void print_element(int i){
  std::cout << i << std::endl;
}

int main(){
  using namespace std;

  list<int> lst;
  lst.push_back(7);   lst.push_back(9);  lst.push_back(8);  lst.push_back(1);  lst.push_back(-1);

  // The two first parameters are iterators:
  for_each(lst.begin(), lst.end(), print_element);   // 7 9 8 1 -1
}