1. 程式人生 > >C++中map按value排序

C++中map按value排序

我們知道C++ STL中的map是以key排序的。

int main()
{
    map<int, int> iMap;
    iMap[1] = 20;
    iMap[2] = 10;
    iMap[5] = 30;
    iMap[4] = 0;
    for (auto it = iMap.begin(); it != iMap.end(); it++)
        cout << it->first << ':' << it->second << '\n';
    return 0;
}

執行結果:
map執行結果

那如果我要以value進行排序呢?
方案:將map的key和value以pair的形式裝到vector中,對vector進行排序。
(下面使用unordered_map,而沒有使用map)

int main()
{
    unordered_map<int, int> iMap;
    iMap[1] = 20;
    iMap[2] = 10;
    iMap[5] = 30;
    iMap[4] = 0;

    vector<pair<int, int>> vtMap;
    for (auto it = iMap.begin(); it != iMap.end(); it++)
        vtMap.push_back(make_pair(it->first, it->second));

    sort(vtMap.begin(), vtMap.end(), 
        [](const
pair<int, int> &x, const pair<int, int> &y) -> int { return x.second < y.second; }); for (auto it = vtMap.begin(); it != vtMap.end(); it++) cout << it->first << ':' << it->second << '\n'; return 0; }

執行結果:
unordered_map執行結果
這是從小大的排序結果,如果想要從大到小的排序,將sort函式中的第三個引數中Lambda表示式重點額函式體修改為:return y.second < x.second;即可!