日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

詳解C++?functional庫(kù)中的仿函數(shù)使用方法_C 語(yǔ)言

作者:Aatrowen ? 更新時(shí)間: 2022-06-09 編程語(yǔ)言

一、仿函數(shù)簡(jiǎn)介

仿函數(shù)(functor)又稱之為函數(shù)對(duì)象(function object),實(shí)際上就是 重載了()操作符 的 struct或class。
由于重載了()操作符,所以使用他的時(shí)候就像在調(diào)用函數(shù)一樣,于是就被稱為“仿”函數(shù)啦。

二、仿函數(shù)簡(jiǎn)要寫法示例

一個(gè)很正常的需求,定義一個(gè)仿函數(shù)作為一個(gè)數(shù)組的排序規(guī)則:

將數(shù)組從大到小排序

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

使用

vector 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++自帶的仿函數(shù)

在C++ 的functional頭文件中,已經(jīng)為我們提供好了一些仿函數(shù),可以直接使用。

(1)算術(shù)仿函數(shù)

1.plus 計(jì)算兩數(shù)之和

例:將兩個(gè)等長(zhǎng)數(shù)組相加

    vector 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());

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

輸出

2 4 6 8 10 12 14 16 18 20

2.minus 兩數(shù)相減

將上面那個(gè)例子改一改:

transform(begin(a), end(a), begin(b), begin(a), minus());

輸出

0 0 0 0 0 0 0 0 0 0

3.multiplies 兩數(shù)相乘

再將上面那個(gè)例子改一改:

transform(begin(a), end(a), begin(b), begin(a), multiplies());

輸出

1 4 9 16 25 36 49 64 81 100

4.divides 兩數(shù)相除

還將上面那個(gè)例子改一改:

transform(begin(a), end(a), begin(b), begin(a), divides());

輸出

1 1 1 1 1 1 1 1 1 1

5.modules 取模運(yùn)算

繼續(xù)將上面那個(gè)例子改一改:

transform(begin(a), end(a), begin(b), begin(a), modulus());

輸出

0 0 0 0 0 0 0 0 0 0

6.negate 相反數(shù)

這次不能那樣改了,因?yàn)樯鲜龅奈鍌€(gè)仿函數(shù)是二元仿函數(shù),是對(duì)兩個(gè)操作數(shù)而言的。

negate是一元仿函數(shù),只能對(duì)一個(gè)參數(shù)求相反數(shù)。

所以我們對(duì)a數(shù)組求相反數(shù):

transform(begin(a), end(a), begin(a), negate());

輸出

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

(2)關(guān)系仿函數(shù)

1.equal_to 是否相等

2.not_equal_to 是否不相等

3.greater 大于

4.less 小于

5.greater_equal 大于等于

6.less_equal 小于等于

到這時(shí),我們就可以看出,可以使用 greater() 來(lái)代替我們開(kāi)頭實(shí)現(xiàn)的例子

將數(shù)組從大到小排序:

vector a(10);
iota(begin(a), end(a), 1);

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

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

輸出

10 9 8 7 6 5 4 3 2 1

(3)邏輯仿函數(shù)

1.logical_and 二元,求&

2.logical_or 二元,求|

3.logical_not 一元,求!

使用方法同上.

話說(shuō),并沒(méi)有發(fā)現(xiàn)求異或的仿函數(shù)..

原文鏈接:https://www.cnblogs.com/Aatrowen-Blog/p/16112067.html

欄目分類
最近更新