对c++中的哈希表(map)分别根据key和value排序

因为刚刚接触c++不是很久 在用的时候有些困难
然后今天在刷题的时候 遇到一个需要对哈希表排序的操作
然后研究了很长时间在
这里和大家分享一下
可以根据不同的要求 对于key和value来排序
里边需要用到pair的知识 这个方法可以用偷梁换柱来形容
我们就用vector<pair<int,int>>来代替map<int,int>
我们说的map中的key和value就用first和second来代替了


bool cmp1(pair<int, int> a, pair<int, int> b) {
    return a.first < b.first;//对于first的升序
}
bool cmp2(pair<int, int>a, pair<int, int> b) {
    return a.second < b.second;//对于second的升序
}
int main()
{
    map<int, int> hash;
    hash[1] = 4;
    hash[3] = 3;
    hash[2] = 5;
    hash[4] = 1;
    vector<pair<int, int>> vecs;
    for (auto it = hash.begin();it!= hash.end();it++) {
        vecs.push_back(make_pair(it->first, it->second));
   }
     //对于first升序排列
    cout << "对于first升序排列:" << endl;
    sort(vecs.begin(), vecs.end(),cmp1);
    for (auto it = vecs.begin(); it != vecs.end(); it++)
        cout << it->first << ':' << it->second << '\n';
    //对于second升序排列
    cout << "对于second升序排列:" << endl;
    sort(vecs.begin(), vecs.end(), cmp2);
    for (auto it = vecs.begin(); it != vecs.end(); it++)
        cout << it->first << ':' << it->second << '\n';
    return 0;
}

其实很好理解的

运行截图
在这里插入图片描述

案例

在这里插入图片描述

typedef pair<int, int> vecs;
vector<vecs>ans;
vector<int>res;
bool cmp(vecs a, vecs b) {
    if (a.first != b.first)return a.first < b.first;//按1的个数
    else return a.second < b.second;//如果1的个数相同 按原本顺序
}
vector<int> sortByBits(vector<int>& arr) {
    for (auto e : arr)
    {
        int c = e;
        int cnt = 0;
        while (e) {
            if (e % 2 == 1)cnt++;
            e /= 2;
        }
        ans.push_back({ cnt,c });
    }
    sort(ans.begin(), ans.end(), cmp);
    for (auto e : ans)res.push_back(e.second);

    return res;
}
   

在这里插入图片描述

class Solution {
public:
 static bool cmp(pair<int, int> a, pair<int, int> b) {
    if (a.second == b.second) {
        return a.first > b.first;
    }
    else {
        return a.second < b.second;
    }
}
vector<int> frequencySort(vector<int>& nums) {
    map<int, int> hash;
    for (int i = 0; i < nums.size(); i++) {
        hash[nums[i]]++;
    }
    vector<pair<int, int>> vecs;
    for (int i = 0; i < nums.size(); i++) {
        vecs.push_back({ nums[i],hash[nums[i]] });
    }
    sort(vecs.begin(), vecs.end(), cmp);
    vector<int> ans;
    for (auto a : vecs) {
        ans.push_back(a.first);
    }
    return ans;
}
};
  • 13
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值