c 學習筆記12

2021-10-02 10:16:50 字數 3658 閱讀 8912

概念:

過載函式呼叫操作符的類,其物件稱為函式物件

函式物件使用過載的()時,行為類似函式呼叫,也叫仿函式

本質:函式物件(仿函式)是乙個類,不是乙個函式

特點:函式物件在使用時,可以像普通函式那樣呼叫,可以有引數,可以有返回值

函式物件超出普通函式的概念,函式物件可以有自己的狀態

函式物件可以作為引數傳遞

**:

#include

using

namespace std;

//函式物件(仿函式)

class

myadd};

//1.函式物件在使用時可以像普通函式那樣呼叫,可以有引數,可以有返回值

void

test01()

//2.函式物件超出普通函式的概念,函式物件可以有自己的狀態

class

myprint

void

operator()

(string test)

int count;};

void

test02()

//3.函式物件可以作為引數傳遞

void

doprint

(myprint &mp,string test)

void

test03()

intmain()

概念:

返回bool型別的仿函式稱為謂詞

如果operator()接受乙個引數,那麼叫做一元謂詞

如果operator()接受兩個引數,那麼叫做二元謂詞

一元謂詞

#include

using

namespace std;

#include

#include

//仿函式 返回值型別 是bool型別,稱為謂詞

//一元謂詞

class

greaterfive};

void

test01()

//查詢容器中有沒有大於5的數字

//greaterfive() 匿名函式物件

vector<

int>

::iterator it =

find_if

(v.begin()

, v.

end(),

greaterfive()

);if(it == v.

end())

else

}int

main()

二元謂詞
#include

using

namespace std;

#include

#include

//二元謂詞

class

mycompare};

void

test01()

cout << endl;

//使用函式物件 改變演算法策略 變為從大到小排序

sort

(v.begin()

, v.

end(),

mycompare()

);cout <<

"-------------------------------------------"

<< endl;

for(vector<

int>

::iterator it = v.

begin()

; it != v.

end(

); it++

) cout << endl;

}int

main()

概念:

stl內建了一些函式物件

分類:算數仿函式

關係仿函式

邏輯仿函式

用法:這些仿函式所產生的物件,用法和一般的函式完全相同

使用內建函式物件,需要引入標頭檔案#include

算數仿函式

實現四則運算

#include

using

namespace std;

#include

//內鍵函式物件標頭檔案

//內建函式物件 算數仿函式

//negate 一元仿函式 取反仿函式

void

test01()

//plus 二元仿函式 加法

void

test02()

intmain()

關係仿函式

實現關係對比

#include

using

namespace std;

#include

#include

#include

//內建的函式物件 關係仿函式

//大於 greater

class

mycompare};

void

test01()

cout << endl;

//降序

//sort(v.begin(), v.end(), mycompare());

sort

(v.begin()

, v.

end(

), greater<

int>()

);//greater() 內建的仿函式

for(vector<

int>

::iterator it = v.

begin()

; it != v.

end(

); it++

) cout << endl;

}int

main()

邏輯仿函式

實現邏輯運算

#include

using

namespace std;

#include

#include

#include

//內建函式物件 邏輯仿函式

//邏輯非 logical_not

void

test01()

cout << endl;

//利用邏輯非 將容器v搬運到 容器v2中 ,並執行取反操作

vector<

bool

> v2;

v2.resize

(v.size()

);transform

(v.begin()

, v.

end(

), v2.

begin()

, logical_not<

bool

>()

);for(vector<

bool

>

::iterator it = v2.

begin()

; it != v2.

end(

); it++

) cout << endl;

}int

main()

C 學習筆記12

全稱為standard template library,由以下六個部分組成 容器 container,儲存資料 迭代器 iterator,訪問容器中的元素 介面卡 adapter,基礎資料結構 新的資料結構 演算法 algorithm,對容器元素進行操作 函式物件 functor,對元素進行定製化...

C語言學習筆記12

回顧 1.位置指標 作業 1.id判斷 2.根據id顯示人員資訊 預處理指令是c語言支援的一種特殊指令 它們以 做開頭,不以 做結尾 預處理指令在編譯的第乙個階段被處理 所有預處理指令都是把程式變成另外的樣子 gcc可以使用 e選項單獨處理所有預處理指令 define是乙個預處理指令 這個預處理指令...

C 學習筆記12 STL Deque

deque雙端佇列其實就是乙個雙端陣列 deque是雙端佇列,它有vector沒有的功能,push front,在序列頭部新增元素,它的底層設計也不同於vector,deque的底層是用間接索引的方式實現的,如下圖所示 開始的時候map是乙個指標陣列,裡面儲存著若干個指標,但初始的時候只有其中的乙個...