#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;
}
STL —— for_each与仿函数、函数指针
最新推荐文章于 2024-01-13 19:16:55 发布