0
点赞
收藏
分享

微信扫一扫

C++重学(5)——谓词、内建函数对象

草原小黄河 2022-01-28 阅读 50
c++

谓词、内建函数对象

谓词

概念:返回值为bool类型的仿函数

补充:仿函数就是对()进行重载的函数

用途:广泛应用于标准算法<algorithm.h>中,可以为标准算法增加筛选条件

分类:

  • 一元谓词:仿函数的参数数量为1

  • 二元谓词:仿函数的参数数量为2

  class Compare2 {
  public:
  	//二元谓词
  	bool operator()(int val, int val2) {
  		return val > val2;
  	}
  };
  
  void func3() {
  	vector<int> v;
  	//填充vector
  	v.push_back(5);
  	v.push_back(2);
  	v.push_back(6);
  	v.push_back(1);
  	//因为sort是排序算法,核心是两数对比,用二元谓词作为入参,让sort变成降序操作
  	sort(v.begin(), v.end(), Compare2());
  
  	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
  		cout << *it << " ";
  	}
  	cout << endl;
  }

在这里插入图片描述

内建函数对象

概念:STL已经开发好的简单仿函数

头文件:#include <functional>

算数仿函数

除了取反仿函数是一元谓词,其他的都是二元谓词

算术仿函数作用
template T plus加法仿函数
template T minus减法仿函数
template T multiplies乘法仿函数
template T divides除法仿函数
template T modulus取模仿函数
template T negate取反仿函数

关系仿函数

关系仿函数作用
template bool equal_to等于
template bool not_equal_to不等于
template bool greater大于
template bool greater_equal 大于等于
template bool less小于
template bool less_equal 小于等于

逻辑仿函数

逻辑仿函数作用
template bool logical_and
template bool logical_or
template bool logical_not
举报

相关推荐

0 条评论