您的位置:首页 > 其它

STL —— for_each与仿函数、函数指针

2012-03-26 17:33 465 查看
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class PrintInt
{
public:
void operator() (int elem) const
{
cout << elem << '\t';
}
};

class PrintInt2
{
public:
PrintInt2(int x)
: m_x(x)
{ }

void operator() (int elem) const
{
cout << elem + m_x << '\t';
}

private:
int m_x;
};

typedef void (*op)(int &elem);
void Func(int &elem)
{
cout << 2*elem << '\t';
}

int main(void)
{
vector<int> coll;
op p = Func;

for (int i=1; i<=9; i++)
{
coll.push_back(i);
}

for_each(coll.begin(), coll.end(), PrintInt());
cout << endl;

for_each(coll.begin(), coll.end(), PrintInt2(10));
cout << endl;

for_each(coll.begin(), coll.end(), Func);
cout << endl;

for_each(coll.begin(), coll.end(), p);
cout << endl;

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