STL-仿函数

#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;
}

打印结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值