C++学习笔记(22):内建函数对象

0 阅读2分钟

1.内建函数对象意义

概念: STL内建了一些函数对象 分类:

  • 算术仿函数
  • 关系仿函数
  • 逻辑仿函数 用法:
  • 这些仿函数所产生的对象,用法和一般函数完全相同
  • 使用内建函数对象,需要引用头文件#include

2.算术仿函数

功能: 实现四则运算,其中negate是一元运算,其他则是二元运算
仿函数原型:
template<class T> T plus<T>       //加法仿函数
template<class T> T minus<T>      //减法仿函数
template<class T> T multiplies<T>   //乘法仿函数
template<class T> T divides<T>      //除法仿函数
template<class T> T modulus<T>      //取模仿函数
template<class T> T negate<T>       //取反仿函数

3.关系仿函数

template<class T> bool equal_to<T>    //等于
template<class T> bool not_equal_to<T>   //不等于
template<class T> bool greater<T>       //大于
template<class T> bool greater_equal<T>    //大于等于
template<class T> bool less<T>           //小于
template<class T> bool less_equal<T>      //小于等于

4.template bool logical_and //逻辑与

template<class T> bool logical_or<T>    //逻辑或
template<class T> bool logical_not<T>    //逻辑非

5.

一、是什么

  • 头文件:  
  • C++ 标准库自带的、现成的函数对象类
  • 用来替代手写简单的函数、lambda,配合算法( sort / find_if / transform  等)用

二、分类(必背)

  1. 算术类(二元)
  •  plus  : a + b 
  •  minus  : a - b 
  •  multiplies  : a * b 
  •  divides  : a / b 
  •  modulus  : a % b 
  •  negate  : -a (一元)
  1. 关系比较类(二元,返回 bool)
  •  equal_to  : a == b 
  •  not_equal_to  : a != b 
  •  greater  : a > b 
  •  greater_equal : a >= b 
  •  less  : a < b (sort 默认)
  •  less_equal  : a <= b 
  1. 逻辑运算类(返回 bool)
  •  logical_and  : a && b 
  •  logical_or  : a || b 
  •  logical_not  : !a (一元)

三、怎么用(极简示例)

cpp

#include #include #include using namespace std;

vector v = {3,1,4,1,5};

// 降序排序:用 greater() sort(v.begin(), v.end(), greater());  

cpp

// 累加:plus() int sum = accumulate(v.begin(), v.end(), 0, plus());  

四、核心特点

1. 是类,使用时要加  ()  生成对象

  • 正确: greater() 
  • 错误: greater  2. 配合 STL 算法 最常用: sort  /  find_if  /  accumulate  /  transform  3. C++11 后常用 lambda 替代,但面试、底层代码、老项目还经常考 4. 是函数对象(仿函数),可以被内联,比函数指针快

五、高频考点一句话

  • 内建函数对象就是 STL 提供的仿函数,用来做算术、比较、逻辑运算,配合算法使用。
  • 最常考: greater()  实现降序排序。