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;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM