首页 > 学院 > 开发设计 > 正文

algorithm中for_each用法

2019-11-08 02:20:47
字体:
来源:转载
供稿:网友

algorithm中for_each用法

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);}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表