您的位置:首页 > 编程语言 > Go语言

STL (1)for_each 函数

2013-11-22 10:19 375 查看
/*
// TEMPLATE FUNCTION for_each
//
template<class _InIt,
class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{	// perform function for each element
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Func);
_CHECKED_BASE_TYPE(_InIt) _ChkFirst(_CHECKED_BASE(_First));
_CHECKED_BASE_TYPE(_InIt) _ChkLast(_CHECKED_BASE(_Last));
for (; _ChkFirst != _ChkLast; ++_ChkFirst) //利用_ChkFirst移动迭代器
_Func(*_ChkFirst);   //每个元素都执行函数_Func
return (_Func);
}

*/

//*********************by vincent http://my.csdn.net/sunboyiris  ************************//
#include "stdafx.h"
#include "algorithm"
#include "list"
#include "iostream"
using namespace std;
struct print
{
int count;
print(){count=0;}
void operator()(int x)
{
cout<<x<<endl;
count++;
}
};
void print1(int& i)
{
cout<<i<<endl;

}

void print2(int i,const char* ptr)
{
cout<<ptr<<" : "<<i<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
list<int> l;
for(int i=0;i<10;i++)
{
l.push_back(i);
}
//引用指针
int count1=0;
list<int>::iterator iter;
for(iter=l.begin();iter!=l.end();iter++)
{
count1++;
}
cout<<count1<<endl;

//----------------不传入参数--------//
print p=for_each(l.begin(),l.end(),print());
cout<<"the number is :"<<p.count<<endl;

//----------------不传入参数--------//
for_each(l.begin(),l.end(),print1);

//----------------传入参数--------//
for_each(l.begin(),l.end(),bind2nd(ptr_fun(print2),"the number is "));

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  stl algorithm each