#include<vector>
#include<algorithm>
#include<functional>//内建的仿函数
#include<iostream>
using namespace std;
//函数对象(仿函数):重载了()的类就是仿函数
struct MyPrint
{
void operator()(int val)
{
cout << val << endl;
}
};
void test1()
{
MyPrint p;
p(10);
}
struct Fun
{
Fun()
{
count = 0;
}
void operator()()
{
cout << "hello" << endl;
++count;
}
public:
int count;
};
void test2()
{
Fun fun;
fun();
fun();
fun();
cout << fun.count << endl;
}
//谓词:函数对象返回值是bool类型的叫谓词
struct GreaterThanFive
{
bool operator()(int val)
{
return val > 5;
}
};
//一元谓词:一个参数
void test3()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
vector<int>::iterator ret=find_if(v.begin(), v.end(), GreaterThanFive());
if (ret == v.end())
{
cout << "没有找到" << endl;
}
else
{
cout << "大于5的有:"<<*ret << endl;
}
}
//内建的仿函数
void test4()
{
plus<int> myplus;
cout << myplus(10, 20) << endl;
vector<int> v;
v.push_back(2);
v.push_back(1);
v.push_back(8);
v.push_back(5);
v.push_back(10);
sort(v.begin(), v.end(), greater<int>());
//第三个参数是lambda表达式
for_each(v.begin(), v.end(), [](int val){cout << val << " "; });
}
int main()
{
//test1();
//test2();
//test3();
test4();
system("pause");
return 0;
}
打印结果: