for_each算法

算法详解

for_each( )算法非常的灵活,它可以不用的方式存取,处理,修改每一个元素。

接口
Function for_each(InputIterator _First, InputIterator _Last, Function _Func)
参数
_First, 指定容器的起始位置
_Last ,指定容器的最后一个元素的下一个位置
_Func 用户自行定义的函数或者仿函数,_Func会作用于容器内的每个元素

返回值
返回_Func 的一个副本,一般该返回值都会被忽略

复杂度
线性

算法实现
template<class InputIterator, class Function>
Function for_each(InputIterator _First, InputIterator _Last, Function _Func)
{
	while (_First != _Last)
	{
		_Func(*_First);	//call _Func() for actual element
		_First++;
	}

	return (_Func);
}

应用

#include "stdafx.h"
#include <string.h>
#include <algorithm>
#include <vector>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <sstream>
#include <iterator>
#include <functional>
#include <stdlib.h>
#define  MAX_NUM 10

//#include "print.h"
using namespace std;

//function called for each element
void Print(int elem)
{
	cout << elem << ' ';
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vecCollection;
	for (int i = 0; i < MAX_NUM; ++i)
	{
		vecCollection.push_back(i);
	}
	
	//call Print() for each element
	for_each(vecCollection.begin(), vecCollection.end(), Print);

	cout << endl;
}

输出:

转载于:https://www.cnblogs.com/jinxiang1224/p/8468429.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值