![]() ![]() ![]() | Implementation and sample use of for-each on a list of integers. | Lecture 5 - slide 34 : 39 Program 2 |
#include <iostream> #include <string> #include <list> template <class In, class Op> Op for_each(In first, In last, Op 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 }