标准库sort函数自定义排序

自定义排序
sort函数第三个参数compare,为自定义比较函数指针,原型如下:

bool cmp(const Type &a, const Type &b);
如果是想升序,那么就定义当a<b的时候返回true;
如果是想降序,那么就定义当a>b的时候返回true;

注意compare函数写在类外或者定义为静态函数
std::sort要求函数对象,或是静态/全局函数指针,非静态成员函数指针不能直接传递给std::sort。

示例

bool cmp(const pair<int,int> &a, const pair<int,int> &b)
{
    return a.second>b.second;
}

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;        
        unordered_map<int, int> countMap;

        for (auto item:nums) {
            countMap[item]++;
        }

        vector<pair<int, int>> countVec(countMap.begin(), countMap.end());

//        sort(countVec.begin(), countVec.end(), [](const pair<int,int> &a, const pair<int,int> &b){
//            return a.second>b.second;
//        });

        sort(countVec.begin(), countVec.end(), cmp);

        for (int i=0;i<k;i++) {
            res.push_back(countVec[i].first);
        }

        return res;
    }
};
posted @ 2021-07-04 21:56  hunter-w  阅读(783)  评论(0编辑  收藏  举报