C++——使用仿函數實現map的降序排序

在頭文件xfunctional裏有兩個仿函數greaterless,是STL實現的用以升/降序的比較操作。

使map按關鍵字降序排列:

map<int,int,greater<int>> mp;

但是如果map內的數據元素是自定義數據結構,則不能使用這種方式,需要老老實實自己寫比較函數。

class Person{
    private:
        string name;
        int age;
    public:
        Person(string _n, int _a) : n(_n), a(_a) {};
        //重載<操作符
        bool operator<(const Person &p) const{
            return (age < p.age) || (age == p.age && name.length() < p.name.length()) ;
        }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章