C 之內置函式物件

2021-10-05 10:55:53 字數 2668 閱讀 5398

stl內建了一些函式物件:

算術仿函式

關係仿函式

邏輯仿函式

這些仿函式所產生的物件,用法和一般函式完全相同使用內建函式物件,需要引入標頭檔案 #include

一、算術仿函式

功能描述:

實現四則運算其中negate是一元運算,其他都是二元運算

仿函式原型:

template

<

class

t> t plus

//加法仿函式

template

<

class

t> t minus

//減法仿函式

template

<

class

t> t multiplies

//乘法仿函式

template

<

class

t> t divides

//除法仿函式

template

<

class

t> t modulus

//取模仿函式

template

<

class

t> t negate

//取反仿函式

示例:

#include

//negate取反

void

test01()

//plus

void

test02()

intmain()

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

二、關係仿函式

實現關係對比

仿函式原型:

template

<

class

t>

bool equal_to

//等於

template

<

class

t>

bool not_equal_to

//不等於

template

<

class

t>

bool greater

//大於

template

<

class

t>

bool greater_equal

//大於等於

template

<

class

t>

bool less

//小於

template

<

class

t>

bool less_equal

//小於等於

示例:

#include

#include

#include

class

mycompare

//自定義的,其實greater()乙個道理};

void

test01()

cout << endl;

//這個列印是無序的

//自己實現仿函式

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

//stl內建仿函式 大於仿函式

sort

(v.begin()

, v.

end(

), greater<

int>()

);for(vector<

int>

::iterator it = v.

begin()

; it != v.

end(

); it++

) cout << endl;

//有序

}int

main()

關係仿函式中最常用的就是greater<>大於

三、邏輯仿函式

實現邏輯運算

template bool logical_and //邏輯與

template bool logical_or //邏輯或

template bool logical_not //邏輯非

示例:

#include

#include

#include

void test01()

cout << endl;

//邏輯非 將v容器搬運到v2中,並執行邏輯非運算

vector v2;

v2.resize(v.size());//必須resize,否則會報錯

transform(v.begin(), v.end(), v2.begin(), logical_not());

for (vector::iterator it = v2.begin(); it != v2.end(); it++)

cout << endl;

}int main()

邏輯仿函式實際應用較少,了解即可

C STL 之 內建函式物件

stl 內建了一些函式物件。分為 算數類函式物件,關係運算類函式物件,邏輯運算類仿函式。這些仿函式所產生的物件,用法和一般函式完全相同,當然我們還可以產生無名的臨時物件來履行函式功能。使用內建函式物件,需要引入標頭檔案 include。6 個算數類函式物件,除了 negate 是一元運算,其他都是二...

JS之內置物件

date日期物件 var date new date var date2 new date 2019,07,17 var date3 new date dct 1,2012 date.getdate 獲取日期,setdate 為設定日期 date.getsetfullyear 返回年份 date.g...

python之內置函式

非空即真,非0即真 記住這句話可以讓你少寫好多 l asdfgwert3r 1 sorted l 排序 字串可以直接使用sorted排序 2 all 如果list裡面都為真的情況返回為 true all 1 2,3 4 print true all 1 2,3 0 print false all 1...