algorithm中for_each用法

algorithm中for_each用法

algorithm中for_each用于遍历和执行一些事情,如下代码将打印1-7:

#include
#include
#include
using namespace std;
template <typename T>
class print
{
public:
     void operator()(const T&elem)
     {
          cout<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);
}

你可能感兴趣的:(c++基础)