algorithm中for_each用于遍历和执行一些事情,如下代码将打印1-7:
#include<iostream>#include<vector>#include<algorithm>using namespace std;template <typename T>class PRint{public: void Operator()(const T&elem) { cout<<elem<<endl; }};int main(){ int a[]={1,2,3,4,5,6,7}; vector<int> v(a,a+7); for_each(v.begin(),v.end(),print<int>())//print传入的是函数指针,for_each内部会将迭代器传入函数指针,作为参数运算 ; return 0;}algorithm中for_each实现,代码来自:http://www.cplusplus.com/reference/algorithm/for_each/
template<class InputIterator, class Function> Function for_each(InputIterator first, InputIterator last, Function fn){ while (first!=last) { fn (*first); ++first; } return fn; // or, since C++11: return move(fn);}新闻热点
疑难解答