![]() ![]() ![]() | Implementation and sample use of for-each on an C-style array. | Lecture 5 - slide 34 : 39 Program 1 |
#include <iostream> #include <string> // 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; } void print_element(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+5, print_element); // 7, 9, 8, 1, -1 }