第九层(10):STL之函数对象

简介: 第九层(10):STL之函数对象

前情回顾


在上一块石碑中,我学到了map/multimap,同时下一块石碑也显露出来…


🚄上章地址:第九层(9):STL之map/multimap


函数对象


概念


操作符重载的类,其实例化出来的对象被叫做函数对象

函数对象在重载()时,行为时类似函数调用,也叫仿函数


特点


函数对象在使用时,可以和普通函数一样去调用,也可以有返回值

函数对象可以有自己的状态

函数对象可以作为参数去传递


谓词


概念


返回值为bool类型的仿函数就时谓词,可以根据仿函数的参数分为:一元谓词和二元谓词,谓词常用在算法当中,当参数去传递,当条件去使用


内建函数对象


内建函数对象指的是C++在STL中建立的一些函数对象,可以直接调用使用,使用与函数时一样的,但是在使用的时候要基地引入头文件

#include<functional>


分类


内建函数对象分为三类:

1算术仿函数

2关系仿函数

3逻辑仿函数


算术仿函数


在内建函数对象中提供了算术仿函数,它可以实现四则运算,还有取模和取反的操作

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>//取反仿函数,只需要一个参数


使用:


#include<functional>
#include<iostream>
using namespace std;
int _a, _b;
void test1()
{
  //加法
  plus<int> a;
  cin >> _a >> _b;
  int add = a(_a, _b);
  cout <<"相加后:" << add << endl;
  //减法
  minus<int> b;
  cin >> _a >> _b;
  int min = b(_a, _b);
  cout <<"相减后:" << min << endl;
  //乘法
  multiplies<int> c;
  cin >> _a >> _b;
  int mul = c(_a, _b);
  cout <<"相乘后:" << mul << endl;
  //除法
  divides<int> d;
  cin >> _a >> _b;
  int div = d(_a, _b);
  cout << "相除后" << div << endl;
  //取模
  modulus<int> e;
  cin >> _a >> _b;
  int mod = e(_a, _b);
  cout <<"取模后:" << mod << endl;
  negate<int> f;
  cin >> _a;
  int neg = f(_a);
  cout <<"取反后:" << neg << endl;
}
int main()
{
  test1();
  return 0;
}

0a2653c851af460fa595bd959398a8f1.png


关系仿函数


可以用于比较,比如在排序的时候,像从大到小排,就可以使用大于的仿函数

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


当前者大于后者时候,返回真,小于时返回假,通常可以搭配排序算法去使用


逻辑仿函数


逻辑仿函数指的是与或非三种逻辑

templace<class T> bool logical_and<T>//逻辑与
templace<class T> bool logical_or<T>//逻辑或
templace<class T> bool logical_not<T>//逻辑非


实际用途不大,但是在特定的题中使用可以方便很多


下一座石碑


这座石碑倒下了,露出了下一座石碑…


😘预知后事如何,关注新专栏,和我一起征服C++这座巨塔

🚀专栏:C++爬塔日记

🙉都看到这里了,留下你们的👍点赞+⭐收藏+📋评论吧🙉


相关文章
|
11天前
|
C++ 容器
|
11天前
|
存储 C++ 容器
C++之STL顺序容器
C++之STL顺序容器
|
11天前
|
C++
C++模板与STL【函数对象】
C++模板与STL【函数对象】
|
11月前
|
C++
STL-函数对象(仿函数)
STL-函数对象(仿函数)
41 0
|
算法 编译器 C++
|
C语言 C++ 容器
第九层(2):STL之string类
第九层(2):STL之string类
第九层(2):STL之string类
第九层(3):STL之vector类(上)
第九层(3):STL之vector类(上)
第九层(3):STL之vector类(上)
第九层(3):STL之vector类(下)
第九层(3):STL之vector类(下)
第九层(3):STL之vector类(下)
|
算法 C++ 容器
第九层(5):STL之stack
第九层(5):STL之stack
第九层(5):STL之stack