algorithm—for_each() (1)

std::for_each()                       -<algorithm.h>

 

template <class InputIterator, class Function>
   Function for_each (InputIterator first, InputIterator last, Function f);
 
 
函数功能范围:
应用函数f指向[first, lst)的每一个元素。
     模板函数的作用等效于:
template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function f)
  {
    for ( ; first!=last; ++first ) f(*first);
    return f;
  }
 
参数:
first, last
        输入迭代器指向一个序列的初始和最后位置。使用范围是容器[first, last)内的每一个元素,包括第一个元素但是不        包括最后一个。
f
        该函数调用[first, last)内的一个元素作为参数,指向一个函数或者一个对象的重载操作符()(operator())。此         函数不修改序列内的所有元素。
        
返回值:
        返回f
 
例子:
// for_each example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void myfunction (int i) {
  cout << " " << i;
}

struct myclass {
  void operator() (int i) {cout << " " << i;}
} myobject;

int main () {
  vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  cout << "myvector contains:";
  for_each (myvector.begin(), myvector.end(), myfunction);

  // or:
  cout << "\nmyvector contains:";
  for_each (myvector.begin(), myvector.end(), myobject);

  cout << endl;

  return 0;
}
 
输出:

  
  
myvector contains: 10 20 30
myvector contains: 10 20 30
 
更多高级用法请关注(algorithm—for_each() (2))
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值