0
点赞
收藏
分享

微信扫一扫

C++谓词介绍

芒果六斤半 2022-01-20 阅读 87
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 条评论