您的位置:首页 > 编程语言 > C语言/C++

c++_stl_for_each

2012-11-09 14:38 183 查看
#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 = 0; i< 9; i++)
{
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: