Cpp_learning_note_4

Posted on Jul 4, 2021

[toc]

STL-函数对象

函数对象

  • 概念:重载函数调用操作符的类,其对象称为函数对象;函数对象使用重载的()时,行为类似函数调用,也叫仿函数。
  • 本质:函数对象(仿函数)是一个类,不是一个函数。

函数对象的使用:

  • 可以像普通函数那样调用,可以有参数,可以有返回值
  • 函数对象超出普通函数的概念,函数对象可以有自己的状态
  • 函数对象可以作为参数传递(也可以传递匿名对象)

谓词

A predicate is a function that returns bool (or something that can be implicitly converted to bool). Predicates are widely used in the STL. The comparison functions for the standard associative containers are predicates, and predicate functions are commonly passed as parameters to algorithms like find_if and the various sorting algorithms. – Effective STL

  • 概念:返回bool类型的仿函数称为谓词;如果operator()接收一个参数,称为一元谓词;operator()接收两个参数,称为二元谓词

内建函数对象

  • 概念:STL内建了一些函数对象
  • 分类:算数仿函数、关系仿函数、逻辑仿函数
  • 用法:
    • 这些仿函数所产生的对象,用法和一般函数完全相同
    • 使用内建函数对象,需要引入头文件#include <functional>
  • 算数仿函数 – 实现四则运算、除negete是一元外,其他都是二元运算
    • 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> //取反仿函数
  • 关系仿函数
    • 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> //小于等于
  • 逻辑仿函数
    • template<class T> bool logical_and<T> //逻辑与
    • template<class T> bool logical_or<T> //逻辑或
    • template<class T> bool logical_not<T> //逻辑非

STL-常用算法

  • 算法主要是由头文件<algorithm> <functional> <numeric>组成
  • <algorithm>是所有STL头文件中最大的一个,范围涉及比较、交换、查找、遍历操作、复制、修改等
  • <numeric>体积很小,只包括几个在序列上进行简单数学运算的模板函数
  • <functional>定义了一些模板类,用以声明函数对象

常用遍历算法

  • for_each //遍历容器

函数原型:for_each(iterator beg, iterator end, _func);

_func是函数或者函数对象

  • transform //搬运容器到另一个容器中

transform(iterator beg1, iterator end1, iterator beg2, _func);

tips:搬运的目标容器必须要提前开辟空间,否则无法正常搬运

常用查找算法

  • find //查找元素
  • find_if //按条件查找元素
  • adjacent_find //查找相邻重复元素
  • binary_search //二分查找法
  • count //统计元素个数
  • count_if //按条件统计元素个数

常用排序算法

  • sort //对容器内元素进行排序
  • random_shuffle //洗牌 指定范围内的元素随机调整次序
  • merge // 容器元素合并,并存储到另一容器中
  • reverse // 反转指定范围的元素

常用拷贝算法和替换算法

  • copy // 容器内指定范围的元素拷贝到另一容器中
  • replace // 将容器内指定范围的旧元素修改为新元素
  • replace_if // 容器内指定范围满足条件的元素替换为新元素
  • swap // 互换两个容器的元素

常用算术生成算法

算术生成算法属于小型算法,使用时包含的头文件为 #include <numeric>

  • accumulate // 计算容器元素累计总和
  • fill // 向容器中添加元素

常用集合算法

  • set_intersection // 求两个容器的交集
  • set_union // 求两个容器的并集
  • set_difference // 求两个容器的差集