C++不得不瞭解的知識 函數對象(仿函數)

函數對象基本使用

小劉:喬哥沒在啊,還想問問他什麼是仿函數呢?
宇哥:他呀,就他講的那些東西,誰能聽懂,講的好爛。。
小劉:也是,要不咋倆討論討論?
宇哥:也行,咋倆這水平比那禿子可高多了。


小劉:函數對象是個對象(類),怎麼又有函數,蒙了?
宇哥:不衝突,因爲它又叫仿函數,即類實現了函數的功能

小劉:哦,原來是這樣。那內部咋實現的呢?
宇哥:其實就是類裏面重載了括號。

小劉:這個我知道,上節課剛學的重載。 宇哥:對,本質就是重載,沒那麼高大上。給你看一看代碼 利用仿函數實現了類似函數Add的功能

#include <iostream>
#include<vector>
#include<algorithm> 
using namespace std; 
class Add { 
public: 	
int operator()(int a, int b) { 
		return a + b; 	} 
};
 int main() { 	
 Add add; 
 int sum =add(2, 3); 	
 cout << sum; } 

在這裏插入圖片描述

小劉:那仿函數有什麼特點呢?
宇哥:
在這裏插入圖片描述

謂詞

小劉:這個我知道,爲此就是返回類型爲bool的稱之爲謂詞

宇哥:那考考你,什麼是一元謂詞和二元謂詞
小劉:簡單:一元謂詞就是operator()接受的參數是一個,二元就是兩個
宇哥:聰明!
小劉:就是不太清楚什麼時候使用
宇哥:喬哥下期會講,先看看代碼吧。

#include <iostream>
#include<vector>
#include<algorithm>
 using namespace std; 
 class Compare { 
 public: 
 	bool operator()(int a, int b) { 
 	return a > b; 	
 	} 
 }; 
 int main() { 	
 	Compare  compare; 
 	bool condition =compare(2, 3); 
	cout << condition; }

在這裏插入圖片描述

內建函數對象

需頭文件 #include< functional>

宇哥:內建函數,聽起來好像是,提前寫好的函數
小劉:對的,系統裏提供給我們,直接用就可以了

算術仿函數

在這裏插入圖片描述

小劉:就拿plus舉個例子

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
	plus<int> add;
	int num = add(10, 20);
	cout << num << endl;//30
}

關係仿函數

在這裏插入圖片描述

邏輯仿函數

在這裏插入圖片描述


喬哥:剛纔我聽見有人叫我禿子
小劉,宇哥:哪有,一定是聽錯了。。。
喬哥:好吧,下一次講SLT算法,會用到謂詞哦,這也將是C++的最後一堂課了,不見不散歐
小劉:對了:聽說點讚的人會越來越帥哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章