環(huán)境:ide:Mac+clion
視頻鏈接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5
函數(shù)對(duì)象,也稱為仿函數(shù)。其實(shí)質(zhì)就是重載operator() 來(lái)實(shí)現(xiàn)。
1.可以直接作為函數(shù)調(diào)用。
2.可以操作成員變量。
3.對(duì)象可以作為參數(shù)進(jìn)行傳遞。
class MyAdd{
public:
int operator()(int v1,int v2){ // 這個(gè)被稱為仿函數(shù)或者函數(shù)對(duì)象。
return v1 + v2;
}
};
class MyPrint{
public:
MyPrint():m_Count(0){
}
void operator()(string msg){//這個(gè)也是仿函數(shù)。
cout << msg<<endl;
this->m_Count++;
}
int m_Count;
};
void doPrint(MyPrint &p,string msg){
p(msg);
}
void test(){ // 這是仿函數(shù)或者函數(shù)對(duì)象最簡(jiǎn)單的調(diào)用。
MyAdd myAdd;
int result = myAdd(10,20);
cout << result<< endl;//30
MyPrint myPrint; // 這里事例了利用仿函數(shù),操作類中的成員變量。
myPrint("hello C++");
myPrint("hello C++");
myPrint("hello C++");
cout << myPrint.m_Count<<endl;//3
doPrint(myPrint,"sheik call");// 這里利用仿函數(shù)進(jìn)行參數(shù)傳遞。sheik call
}
謂詞:在仿函數(shù)中,返回值是bool 的值 稱為謂詞。
在operator()中接收一個(gè)參數(shù)叫做一元謂詞。 如果接收兩個(gè)參數(shù)叫做二元謂詞。
class GreaterFive{
public:
bool operator()(int value){//這個(gè)稱之為一元謂詞。
return value > 5;
}
};
void test01(){//謂詞的適用場(chǎng)景。
vector<int>v;//定義一個(gè)vector
for (int i=0;i<10;i++){//插入10個(gè)數(shù)據(jù)
v.push_back(i);
}
//這里的需求是:在容器中查找是否有>5的數(shù) _Pred 看見這個(gè)參數(shù)就是要傳一個(gè)謂詞。
vector<int>::iterator it = find_if(v.begin(),v.end(),GreaterFive());//最后傳遞的參數(shù)是一個(gè)匿名對(duì)象的謂詞。
if (it != v.end()){
cout << "找到大于5的數(shù):"<<*it<<endl;//6
}else{
cout << "沒有找到大于5的數(shù)"<<endl;
}
}
二元謂詞事例:
class MyCompare{
public:
bool operator()(int v1,int v2){//二元謂詞首先返回值是bool,然后是仿函數(shù),然后有兩個(gè)
return v1 > v2;
}
};
void test02(){
vector<int>v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(40);
v.push_back(50);
sort(v.begin(),v.end());// 這里通過默認(rèn)排序,從小到大排序。
for(vector<int>::iterator it=v.begin();it != v.end();it ++){
cout << *it << " " ;//10 20 30 40 50
}
cout << endl;
sort(v.begin(),v.end(),MyCompare());//這里改變排序順序,從大到小。
for(vector<int>::iterator it=v.begin();it != v.end();it ++){
cout << *it << " " ;//50 40 30 20 10
}
cout << endl;
}