【c++ -- 谓词】


谓词

c++中的谓词:返回值为bool类型的仿函数;
一元谓词:operator() 函数接收一个参数;
二元谓词:operator() 函数接收两个参数。

补充函数对象
重载函数调用操作符的类,其对象常称为函数对象。
函数对象使用重载的小括号时,其行为类型函数,因此也叫仿函数。
本质
函数对象是一个类,而非一个函数,我们下面的匿名对象就是一个函数对象。
在这里插入图片描述

(一)一元谓词

在这里插入图片描述
在这里插入图片描述

class Person
{
public:
	bool operator()(int v)  //  一元谓词
	{
		return v > 50;
	}

};

void CoutVector(vector<int>v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
	{
		cout << *it << ' ';
	}
	cout << endl;
}

void test01()
{
	vector<int>v;
	for (int i = 0; i < 6; ++i)
	{
		v.push_back(rand() % 100);
	}

	//  查找大于50的数字
	vector<int>::iterator it = find_if(v.begin(), v.end(), Person());
	cout << " 大于50的数字->";
	if (it != v.end())
		cout << "找到了:" << *it << endl;
	else
		cout << "找不到" << endl;
	CoutVector(v);
	
}

运行实例:
在这里插入图片描述


(二)二元谓词

在这里插入图片描述

class Person
{
public:
	bool operator()(int v)  // 一元谓词
	{
		return v > 0;
	}
	
	bool operator()(int v1, int v2)  // 二元谓词
	{
		return v1 >= v2;
	}
};
	  //  打印函数
void CoutVector(vector<int>v)  
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
	{
		cout << *it << ' ';
	}
	cout << endl;
}

void test02()
{
	vector<int>v;
	for (int i = 0; i < 6; ++i)
	{
		v.push_back(rand() % 100);
	}
	CoutVector(v);
	cout << "升序排序" << endl;
	sort(v.begin(), v.end());
	CoutVector(v);
	cout << "降序排序" << endl;          
	sort(v.begin(), v.end(), Person());  // Person() 是一个匿名函数对象,也就是仿函数
	CoutVector(v); 
}

运行实例:

  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值