C++仿函数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++仿函数

Aatrowen   2022-05-28 我要评论

一、仿函数简介

仿函数(functor)又称之为函数对象(function object),实际上就是 重载了()操作符 的 struct或class。
由于重载了()操作符,所以使用他的时候就像在调用函数一样,于是就被称为“仿”函数啦。

二、仿函数简要写法示例

一个很正常的需求,定义一个仿函数作为一个数组的排序规则:

将数组从大到小排序

class Cmp {
public:
    bool operator()(const int &a, const int &b) {
        return a > b;
    }
};

使用

vector<int> a(10);
iota(begin(a), end(a), 1);

sort(begin(a), end(a), Cmp());  // 使用()

for (auto x : a) {
  cout << x << " ";
}

输出

10 9 8 7 6 5 4 3 2 1

三、使用C++自带的仿函数

在C++ 的functional头文件中,已经为我们提供好了一些仿函数,可以直接使用。

(1)算术仿函数

1.plus 计算两数之和

例:将两个等长数组相加

    vector<int> a(10), b(a);
    iota(begin(a), end(a), 1);
    iota(begin(b), end(b), 1);

    transform(begin(a), end(a), begin(b), begin(a), plus<int>());

    for (auto x : a) {
        cout << x << " ";
    }

输出

2 4 6 8 10 12 14 16 18 20

2.minus 两数相减

将上面那个例子改一改:

transform(begin(a), end(a), begin(b), begin(a), minus<int>());

输出

0 0 0 0 0 0 0 0 0 0

3.multiplies 两数相乘

再将上面那个例子改一改:

transform(begin(a), end(a), begin(b), begin(a), multiplies<int>());

输出

1 4 9 16 25 36 49 64 81 100

4.divides 两数相除

还将上面那个例子改一改:

transform(begin(a), end(a), begin(b), begin(a), divides<int>());

输出

1 1 1 1 1 1 1 1 1 1

5.modules 取模运算

继续将上面那个例子改一改:

transform(begin(a), end(a), begin(b), begin(a), modulus<int>());

输出

0 0 0 0 0 0 0 0 0 0

6.negate 相反数

这次不能那样改了,因为上述的五个仿函数是二元仿函数,是对两个操作数而言的。

negate是一元仿函数,只能对一个参数求相反数。

所以我们对a数组求相反数:

transform(begin(a), end(a), begin(a), negate<int>());

输出

-1 -2 -3 -4 -5 -6 -7 -8 -9 -10

(2)关系仿函数

1.equal_to 是否相等

2.not_equal_to 是否不相等

3.greater 大于

4.less 小于

5.greater_equal 大于等于

6.less_equal 小于等于

到这时,我们就可以看出,可以使用 greater() 来代替我们开头实现的例子

将数组从大到小排序:

vector<int> a(10);
iota(begin(a), end(a), 1);

sort(begin(a), end(a), greater<int>());  // 使用()

for (auto x : a) {
  cout << x << " ";
}

输出

10 9 8 7 6 5 4 3 2 1

(3)逻辑仿函数

1.logical_and 二元,求&

2.logical_or 二元,求|

3.logical_not 一元,求!

使用方法同上.

话说,并没有发现求异或的仿函数..

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们