对一个序列应用函数。可以是函数指针,或者是functor。
// for_each example#include// std::cout#include // std::for_each#include // std::vectorvoid myfunction (int i) { // function: std::cout << ' ' << i;}struct myclass { // function object type: void operator() (int i) {std::cout << ' ' << i;}} myobject;int main () { std::vector myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); std::cout << '\n'; return 0;}