C++谓词介绍

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class GreaterThan
{
public:
	bool operator()(const int& val)
	{
		return val > 20;
	}
};

void test01()
{
	vector<int> v01;
	v01.push_back(20);
	v01.push_back(28);
	v01.push_back(32);
	v01.push_back(290);
	v01.push_back(720);

	vector<int> :: iterator ret =  find_if(v01.begin(), v01.end(), GreaterThan()); //第三个参数为一个匿名的类
	if (ret != v01.end())
	{
		cout << "找到了,大于20的值是:" << *ret << endl;
	}
	else
	{
		cout << "找不到" << endl;
	}
}

class Bigger
{
public:
	bool operator()(const int& val01, const int& val02)
	{
		return val01 > val02;
	}
};

void myPrintInt(const int& val)
{
	cout << val << " ";
}

void test02()
{
	vector<int> v01;
	//v01.insert(0, 100); insert(const_iterator pos, ele); //在迭代器指向的位置pos处插入一个元素ele
	v01.push_back(200);
	v01.push_back(128);
	v01.push_back(322);
	v01.push_back(2390);
	v01.push_back(720);

	//排序:从小到大
	sort(v01.begin(), v01.end());
	for_each(v01.begin(), v01.end(), myPrintInt);
	cout << endl;

	//排序:从大到小
	//lambda表达式:
	sort(v01.begin(), v01.end(), Bigger());
	for_each(v01.begin(), v01.end(), [](const int& val) {cout << val << " "; });
	cout << endl;

	//回调函数不需要把()带上
	//反函数需要把()带上
}

int main()
{
	//谓词:
	//一元谓词:
	test01();

	//二元谓词
	test02();

	return 0;
}

运行结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值