头文件是<functional>
另一种方式是用lambda,写成
for_each(++begin(),end(),[&]{out()}两种方法都需要编译器支持c++11
for_each第三个参数传入的是函数名称,通过模板生成代码后的函数指针,for_each需要调用,可以看看STL的for_each函数的源码。#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std
void print(int a)
{
cout <<a <<"\t"
}
class myInt
{
public:
void operator()(int x)
{
cout <<x <<"\t"
}
}
template<int thevalue>
void add(int &ele)
{
ele += thevalue
}
class AddValue
{
private :
int thevalue
public:
AddValue(int va) : thevalue(va)
{
}
void operator()(int &element)
{
element += thevalue
}
}
int main()
{
/*
vector<string>ve
copy(istream_iterator<string>(cin),
istream_iterator<string>(),
back_inserter(ve))
sort(ve.begin(),ve.end())
copy(ve.begin(),ve.end(),
ostream_iterator<string>(cout,"\t"))
*/
vector<int>ve
for(int i = 0i<9i++)
{
ve.push_back(i)
}
for_each(ve.begin(),ve.end(),print)
cout <<endl
for_each(ve.begin(),ve.end(),myInt())
cout <<endl
cout <<"after add --------" <<endl
for_each(ve.begin(),ve.end(),add<10>)
for_each(ve.begin(),ve.end(),print)
cout <<endl
for_each(ve.begin(),ve.end(),AddValue(10))
for_each(ve.begin(),ve.end(),print)
cout <<endl
for_each(ve.begin(),ve.end(),AddValue(*ve.begin()))
for_each(ve.begin(),ve.end(),print)
cout <<endl
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)