網站首頁 編程語言 正文
一、仿函數簡介
仿函數(functor)又稱之為函數對象(function object),實際上就是 重載了()操作符 的 struct或class。
由于重載了()操作符,所以使用他的時候就像在調用函數一樣,于是就被稱為“仿”函數啦。
二、仿函數簡要寫法示例
一個很正常的需求,定義一個仿函數作為一個數組的排序規則:
將數組從大到小排序
class Cmp { public: bool operator()(const int &a, const int &b) { return a > b; } };
使用:
vectora(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 計算兩數之和
例:將兩個等長數組相加
vectora(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 兩數相減
將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), minus());
輸出:
0 0 0 0 0 0 0 0 0 0
3.multiplies 兩數相乘
再將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), multiplies());
輸出:
1 4 9 16 25 36 49 64 81 100
4.divides 兩數相除
還將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), divides());
輸出:
1 1 1 1 1 1 1 1 1 1
5.modules 取模運算
繼續將上面那個例子改一改:
transform(begin(a), end(a), begin(b), begin(a), modulus());
輸出:
0 0 0 0 0 0 0 0 0 0
6.negate 相反數
這次不能那樣改了,因為上述的五個仿函數是二元仿函數,是對兩個操作數而言的。
negate是一元仿函數,只能對一個參數求相反數。
所以我們對a數組求相反數:
transform(begin(a), end(a), begin(a), negate());
輸出:
-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() 來代替我們開頭實現的例子
將數組從大到小排序:
vectora(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)邏輯仿函數
1.logical_and 二元,求&
2.logical_or 二元,求|
3.logical_not 一元,求!
使用方法同上.
話說,并沒有發現求異或的仿函數..
原文鏈接:https://www.cnblogs.com/Aatrowen-Blog/p/16112067.html
相關推薦
- 2022-03-25 C語言中字符型數據和浮點型數據介紹_C 語言
- 2022-08-15 form表單驗證錯誤提示語太長無法全部展示的問題
- 2022-06-24 React如何使用refresh_token實現無感刷新頁面_React
- 2023-12-16 SpringBoot 配置文件使用@ @取值
- 2022-09-30 Docker容器harbor私有倉庫部署和管理_docker
- 2022-08-26 Docker容器搭建android編譯環境的實踐記錄_docker
- 2022-02-14 el-form的label和表單自適應填滿一行且靠左對齊
- 2022-06-18 Android自定義彈框Dialog效果_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支