zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    redis安装以及php扩展
    Linux下php安装Redis扩展
    正则验证邮箱
    常用方法
    PHPExcel说明
    冒泡排序
    CURL post请求
    PHP生成随机字符串
    PHP中的字符串函数
    PHP中的数组函数
  • 原文地址:https://www.cnblogs.com/hunter-w/p/14970068.html
Copyright © 2011-2022 走看看