• C++标准库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;
        }
    };
    
  • 相关阅读:
    yum安装LAMP
    CentOS7添加永久静态路由
    批量解压缩,显示进度条(2)
    Django静态文件配置
    大家同乐一下,搞了三天的字符串与STL!终于搞好了。。
    C++动态分配空间
    UNICODE问题
    VC编码规范 (转)
    vs2008中添加splash screen[分享]
    E
  • 原文地址:https://www.cnblogs.com/hunter-w/p/14970068.html
Copyright © 2020-2023  润新知