函数对象:一元谓词、二元谓词

本文介绍了C++中函数对象(functor)的概念,通过示例展示了如何创建并使用带有状态的函数对象。同时,讨论了一元谓词和二元谓词在STL中的应用,如在查找和排序操作中自定义比较规则。通过自定义谓词函数,可以灵活地控制容器元素的筛选和排序标准。

1. 函数对象可以有自己的状态。我们可以在类中定义状态变量,这样一个函数对象在多次的调用中可以共享这个状态。但是函数调用没这种优势,除非它使用全局变量来保存状态

2. 函数对象有自己特有的类型,而普通函数无类型可言。这种特性对于使用C++标准库来说是至关重要的。这样我们在使用STL中的函数时,可以传递相应的类型作为参数来实例化相应的模板,从而实现我们自己定义的规则。比如自定义容器的排序规则。

下图为函数对象的程序示例:

#include<iostream>
#include<string>
using namespace std;

//函数对象当普通函数用
class Mymultiplier
{
public:
	Mymultiplier()
	{
		num = 0;
	}
	int operator()(int val)
	{
		num++;
		return val * val;
	}
	int num;//可以定义函数对象内部的状态
};

void Print(const Mymultiplier& m)//不要让m改变,而你m(2)的话,相当于对m做了变动
{
	cout << m.num << endl;
}

void test()
{
	Mymultiplier m1;
	int result=m1(5);//1.像正常的函数对象一样,但是由变量去调用函数
	cout << result<<endl;
	int result1=m1(result);//2.可以调用函数对象内部的状态
	//3.函数对象可以作为参数进行传递
	Print(m1);

}

int main()
{
	test();
	return 0;
	system("pause");
}

 一元谓词、二元谓词

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

//谓词函数是一个返回布尔值的函数。
//一元谓词函数就是只釆用一个实参的函数。使用一元谓词函数可以确定一个给定对象是否具有某些特征。
class Person
{
public:
	Person(string name,int age):c_name(name),c_age(age){}
	string c_name;
	int c_age;
};


class Mydef
{
public:
	bool operator()(Person &p1)
	{
		return p1.c_age > 26;
	}
};

class Mydef1
{
public:
	bool operator()(Person& p1,Person &p2)
	{
		return p1.c_age > p2.c_age;
	}
};


void test()
{
	vector<Person> v;
	v.emplace_back(Person("赵",26));
	v.emplace_back(Person("钱", 27));
	v.emplace_back(Person("孙", 24));
	v.emplace_back(Person("李", 20));
	vector<Person>::iterator it=find_if(v.begin(), v.end(), Mydef());//一元谓词函数
	cout << "姓名:" << (*it).c_name<<"  " <<"   " << (*it).c_age<< endl;

	sort(v.begin(), v.end(), Mydef1());//二元谓词函数
	for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it).c_name << " " << (*it).c_age << endl;
	}
}

int main()
{
	test();
	return 0;
	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值