詳解C++?functional庫中的仿函數(shù)使用方法
一、仿函數(shù)簡介
仿函數(shù)(functor)又稱之為函數(shù)對象(function object),實際上就是 重載了()操作符 的 struct或class。
由于重載了()操作符,所以使用他的時候就像在調(diào)用函數(shù)一樣,于是就被稱為“仿”函數(shù)啦。
二、仿函數(shù)簡要寫法示例
一個很正常的需求,定義一個仿函數(shù)作為一個數(shù)組的排序規(guī)則:
將數(shù)組從大到小排序
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++自帶的仿函數(shù)
在C++ 的functional頭文件中,已經(jīng)為我們提供好了一些仿函數(shù),可以直接使用。
(1)算術(shù)仿函數(shù)
1.plus 計算兩數(shù)之和
例:將兩個等長數(shù)組相加
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 兩數(shù)相減
將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), minus<int>());
輸出:
0 0 0 0 0 0 0 0 0 0
3.multiplies 兩數(shù)相乘
再將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), multiplies<int>());
輸出:
1 4 9 16 25 36 49 64 81 100
4.divides 兩數(shù)相除
還將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), divides<int>());
輸出:
1 1 1 1 1 1 1 1 1 1
5.modules 取模運算
繼續(xù)將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), modulus<int>());
輸出:
0 0 0 0 0 0 0 0 0 0
6.negate 相反數(shù)
這次不能那樣改了,因為上述的五個仿函數(shù)是二元仿函數(shù),是對兩個操作數(shù)而言的。
negate是一元仿函數(shù),只能對一個參數(shù)求相反數(shù)。
所以我們對a數(shù)組求相反數(shù):
transform(begin(a), end(a), begin(a), negate<int>());
輸出:
-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 小于等于
到這時,我們就可以看出,可以使用 greater() 來代替我們開頭實現(xiàn)的例子
將數(shù)組從大到小排序:
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)邏輯仿函數(shù)
1.logical_and 二元,求&
2.logical_or 二元,求|
3.logical_not 一元,求!
使用方法同上.
話說,并沒有發(fā)現(xiàn)求異或的仿函數(shù)..
到此這篇關(guān)于詳解C++ functional庫中的仿函數(shù)使用方法的文章就介紹到這了,更多相關(guān)C++仿函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
老生常談C語言動態(tài)函數(shù)庫的制作和使用(推薦)
下面小編就為大家?guī)硪黄仙U凜語言動態(tài)函數(shù)庫的制作和使用(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08for循環(huán)中刪除map中的元素valgrind檢測提示error:Invalid read of size 8
這篇文章主要介紹了for循環(huán)中刪除map中的元素valgrind檢測提示error:Invalid read of size 8 的相關(guān)資料,需要的朋友可以參考下2016-07-07C++17實現(xiàn)flyweight_factory模板類及使用示例詳解
這篇文章主要為大家介紹了C++17實現(xiàn)flyweight_factory模板類及使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08