谓词,匿名函数

是指普通函数或重载的operator返回值是bool类型的函数对象(仿函数)。

// 仿函数.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include
#include
#include
using namespace std;
class Greater20 {
public:
	bool operator()(int val)
	{
		return val > 20;
	}
};
//一元谓词
void test01()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);
	v.push_back(50);
	v.push_back(60);

	//查第一个大于20的数
	//disange参数 函数对象 
	//find_if(v.begin(), v.end(), Greater20());//匿名对象
	/*
	Greater20 g;
	find_if(v.begin(), v.end(), g);//非匿名
	*/
	//find_if的返回值是迭代器
	vector<int>::iterator it= find_if(v.begin(), v.end(), Greater20());
	if (it != v.end())
	{
		cout << "找到了第一个大于20的数字" << *it << endl;
	 }
	else {
		cout << "未找到" << endl;
	}

}
//二元谓词
class Mycompare {
public:
	bool operetor(int v1, int v2)
	{
		return v1 > v2;
	}
};
void test02()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);
	v.push_back(50);
	v.push_back(60);

	sort(v.begin(), v.end(), Mycompare());
	//匿名函数  lambda表达式[](){}//[]是标识符  ()放参数  {}放实现
	for_each(v.begin(), v.end(), [](int val) {cout << val << "  "; });
}
int main()
{
	
    return 0;
}


你可能感兴趣的:(c++)