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

其實很好理解的

運行截圖
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章