C++标准库sort函数自定义排序


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

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

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

示例

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

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

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

        vector> countVec(countMap.begin(), countMap.end());

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

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

        for (int i=0;i