理解仿函式

2021-09-08 14:19:30 字數 1820 閱讀 7821

1、考慮下面的需求,vector中放置person,person有age和name欄位。在vector中查詢第乙個person c,這個很簡單,方法如下:

vector::iterator iter = find(personvector.begin(),personvector.end(),c);

注意:find演算法使用操作符==,比較物件是否相等,需要提供==過載。

2、考慮下面的需求,在vector中查詢第乙個age>15的person。使用find_if和仿函式。如下:

iter = find_if(personvector.begin(),personvector.end(),getbigagefunctor(15));

3、完整**如下:

person.h

1

#ifndef person_h__

2#define person_h__

34 #include

5 #include 6

using

namespace

std;78

class

person9;

32#endif

view code

person.cpp

1 #include 

2 #include "

stdafx.h"3

4person::person()57

8 person::person(const

int& age,const

string&name):age(age),name(name)911

12int person::getage() const

1316

17void person::setage(const

int&age)

1821

22string person::getname() const

2326

27void person::setname(const

string&name)

2831

32bool person::operator==(const person&rhs)

3336

37 person::operator

int() const

38

view code

main.cpp

1

class

getbigagefunctor210

11bool

operator()(const person&person)

1215

};16

1718

int _tmain(int argc, _tchar*ar**)

19

view code

4、操作符過載分為普通操作符和成員操作符,相對於普通操作符,成員操作符少了乙個左運算元,成員操作符的左運算元就是成員方法中的this。

5、操作符過載,仿函式,隱式型別轉換操作符分別為:  

bool operator==(const person& rhs)   操作符過載,可以認為operator== 就是方法名。

bool operator()(const person& person) 仿函式可以認為是一種特殊的操作符過載,也就是過載了操作符()

operator int() const; 隱式型別轉換操作符,可以認為沒有形參,沒有返回型別(類似構造方法),好像是過載了int  

注意:一般情況下,不要使用隱式型別轉換(構造方法加上explicit),也不要提供隱式型別轉換操作符(可以提供as***方法),因為他們實現了不合理的需求。

c 中仿函式的理解

2016年11月11日 17 47 25 1341人閱讀收藏 舉報c 基礎 7 先考慮乙個簡單的例子 假設有乙個vector,你的任務是統計長度小於5的string的個數,如果使用count if函式的話,你的 可能長成這樣 1 bool lengthislessthanfive const str...

python 仿函式 C 仿函式

c 的標準庫stl裡面有6大部件,其中之一為仿函式。初始看到這一名字可能讓人摸不著頭腦 函式倒是挺容易理解,何故又起個仿函式的名字呢?本文將帶你揭開它看起來挺讓人迷惑但是實際上很簡單的面紗。仿函式,看名字就知道它肯定和函式有什麼關聯,但是也肯定和函式有什麼區別。函式主要是一塊接收輸入引數然後按照一定...

在C 中對仿函式的理解

先考慮乙個簡單的例子 假設有乙個vector,你的任務是統計長度小於5的string的個數,如果使用count if函式的話,你的 可能長成這樣 bool lengthislessthanfive const string str int res count if vec.begin vec.end...