簡體   English   中英

排序std :: unordered_map <std::string, std::atomic<unsigned int> &gt;按值

[英]Sort std::unordered_map<std::string, std::atomic<unsigned int>> by values

我有std::unordered_map<std::string, std::atomic<unsigned int>>

我想打印鍵和值,按值排序。
我遇到的最好的解決方案是創建一個向量對並對其進行排序

但是由於無法復制std::atomic<unsigned int> ,最有效的解決方案是什么?

將數據的副本復制到向量中是可以的,但是您需要提供一個自定義操作,該操作在您的atomic<unsigned>上調用load()使其成為普通的unsigned 由於無論如何您都被迫這樣做,因此不妨反轉成對詞條的順序:

std::vector<pair<unsigned int,std::string>> copy;
std::transform(
    m.begin()
,   m.end()
,   back_inserter(copy)
,   [](const pair<const std::string, std::atomic<unsigned int>>& p) {
        return make_pair(p.second.load(), p.first);
    }
);

現在值是第一個,對std::sort的調用不再需要自定義比較器:

std::sort(copy.begin(), copy.end());

演示

另一種解決方案是將unordered_map復制到以值為鍵的multimap ,然后將其打印出來:

#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
#include <atomic>
#include <algorithm>
#include <iterator>

int main()
{
    std::unordered_map<std::string, std::atomic<unsigned int>> m;
    for (auto p : std::initializer_list<std::pair<std::string, unsigned int>>{{ "a", 32},{ "b" , 22 },{ "c" , 32 },{ "d" , 22 },{ "e" , 55 } })
        m.emplace(p);

    std::multimap<unsigned int, std::string> printmap;

    std::transform(m.begin(), m.end(), std::inserter(printmap, printmap.end()),
        [](auto const &p) { return std::make_pair(p.second.load(), p.first); });

    for (auto const &p : printmap)
        std::cout << p.first << " - " << p.second << std::endl;

    return 0;
}

演示: https : //ideone.com/MgtMY8

22 - d
22 - b
32 - c
32 - a
55 - e

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM