C lambda 和 函式物件

2021-10-10 07:29:25 字數 2174 閱讀 5724

//

#include

#include

#include

#include

#include

#include

using

namespace std;

intadd

(const

int& a,

const

int& b)

intsub

(const

int& a,

const

int& b)

struct mulitiply };

intmy_process

(const

int& a,

const

int& b,

decltype

(add) f)

intmain()

;// 定義 cc變數名的函式

int(

*cc)

(const

int& a,

const

int& b)

= sub;

cout <<

my_process(3

,3, ad)

my_process(3

,3, cc)

<< endl;

// 這時候 可呼叫的函式物件是無法使用的,包括lambda表示式型別

// 使用函式表

function<

int(

const

int&

,const

int&

)> fa;

fa = add;

// 函式

fa = sub;

// 函式

fa = cc;

// 函式指標

// key 返回值 引數列表

map < string, function<

int(

const

int&

,const

int&

)>> mapfuncitem;

mapfuncitem.

emplace

("+"

, add)

; mapfuncitem.

emplace

("-"

, std::minus<

int>()

);mapfuncitem.

emplace

("*"

,mulitiply()

);mapfuncitem.

emplace

("/",[

](const

int& a,

const

int& b));

mapfuncitem.

emplace

("%"

, mod)

;auto funproc =

(const

int& a,

const

int& b, function<

int(

const

int&

,const

int&

)> f)

; cout <<

"function 呼叫 + :"

<<

funproc(12

,14, mapfuncitem[

"+"]);

cout <<

"function 呼叫 - :"

<<

funproc(12

,14, mapfuncitem[

"-"]);

cout <<

"function 呼叫 * :"

<<

funproc(12

,14, mapfuncitem[

"*"]);

cout <<

"function 呼叫 / :"

<<

funproc(12

,14, mapfuncitem[

"/"]);

cout <<

"function 呼叫 % :"

<<

funproc(12

,14, mapfuncitem[

"%"]);

}

C lambda 函式物件 函式指標(函式名)

stl演算法中通常會傳入乙個謂詞來實現自定義的排序,查詢數值等行為。lambda 函式物件 函式指標 函式名 均可以在這個情境中傳遞資訊。在這種情境下對比一下三者的使用 1.傳入函式指標 函式名 例如,count if 函式的第三個引數是乙個一元謂詞。若判數乙個數能否被3整除,則定義函式 bool ...

C lambda函式總結

c11新增加的特性,不過現在都c20了不新了。捕捉列表 引數 屬性 返回值型別引出符 因為lambda無法直接使用區域性變數,所以需要對變數進行捕捉,也就是需要通過捕捉列表通知c 這些變數我要拿來用。包含幾種不同的形式 形式 作用 x 表示以值傳遞的方式獲得變數x 表示以值傳遞的方式獲取所有父作用域...

c Lambda 函式形式及用法

宣告 本文參考了 和 lambda函式又稱lambda函式和匿名函式,是c 11新加入的乙個十分強大的特性。在程式設計中經常可以用到。我們可以這樣定義乙個lambda函式 include int main 省略函式型別 auto f2 int 函式型別後置 其中f1即可呼叫或者作為引數被傳入 類似於...