algorithm中for_each用法

来源:互联网 发布:php curl 发送请求头 编辑:程序博客网 时间:2024/06/05 21:03

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);}
0 0