#include<algorithm>
#include<iostream>
#include<functional>
#include<string>
using namespace std;
class student{
public:
student(){}//這個構造函數是必需的,因爲sort的第三個參數需要一個默認的student對象即可
student(int x, string str){
age=x;
name=str;
}
int age;
string name;
bool operator()(const student &a,const student &b){
//因爲sort的第三個參數需要的函數是一個二元的關係運算符,所以這個函數的原型也應該如此給出
//這決定了函數的形參列表和函數返回值的型了
return a.age>b.age?true:false;
}
/*因爲要對student的對象進行sort處理,對於student對象的比較規則必需要自己告知編譯器才行
重載了student的()運算符,這樣只要有student的對象,就能拿到student的比較規則。
*/
};
student stu[3]={student(12,"h"),student(13,"dfd"),student(10,"huaxia")};
void main(){
sort(stu,stu+3,student());
for(int i =0;i<3;++i)
cout << stu[i].age << ' ' << stu[i].name << endl;
}
仿函數,即函數對象,的一個簡單例子
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.