簡體   English   中英

按鍵排序 std::unordered_map

[英]Sorting std::unordered_map by key

如何按鍵排序unordered_map 我需要打印一個按鍵排序的unordered_map

std::unordered_map<int, int> unordered;

std::map<int, int> ordered(unordered.begin(), unordered.end());
for(auto it = ordered.begin(); it != ordered.end(); ++it)
     std::cout << it->second;

另一種解決方案是構造一個鍵向量,對向量進行排序,然后按照排序后的向量進行打印。 這將比從訂購的 map 構建 map 的方法快得多,但也會涉及更多代碼。

std::unordered_map<KeyType, MapType> unordered;
std::vector<KeyType> keys;

keys.reserve (unordered.size());
for (auto& it : unordered) {
    keys.push_back(it.first);
}
std::sort (keys.begin(), keys.end());
for (auto& it : keys) {
    std::cout << unordered[it] << ' ';
}

確定你需要這個嗎? 因為那是不可能的。 一個unordered_map是一個 hash 容器,也就是說,鍵是散列的。 在容器內部,它們與外部的表示不同。 甚至名稱也暗示您無法對其進行排序。 這是選擇 hash 容器的標准之一:您不需要特定的訂單。

如果你這樣做了,得到一個正常的map 鍵自動按嚴格-弱排序進行排序。 如果您需要另一種排序,請編寫自己的比較器。

如果您只需要將其打印排序,則以下可能效率低下,但如果您仍想保留unordered_map ,它會盡可能接近。

#include <map>
#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <functional>

struct map_streamer{
  std::ostream& _os;

  map_streamer(std::ostream& os) : _os(os) {}

  template<class K, class V>
  void operator()(std::pair<K,V> const& val){
    // .first is your key, .second is your value
    _os << val.first << " : " << val.second << "\n";
  }
};

template<class K, class V, class Comp>
void print_sorted(std::unordered_map<K,V> const& um, Comp pred){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}

template<class K, class V>
void print_sorted(std::unordered_map<K,V> const& um){
  print_sorted(um, std::less<int>());
}

Ideone 上的示例
請注意,在 C++0x 中,您可以使用默認模板參數將兩個重載替換為一個 function:

template<class K, class V, class Comp = std::less<int> >
void print_sorted(std::unordered_map<K,V> const& um, Comp pred = Comp()){
  std::map<K,V> m(um.begin(), um.end(), pred);
  std::for_each(m.begin(),m.end(),map_streamer(std::cout));
}

與大衛的回答類似,我們可以先使用std::set對鍵進行排序:

std::unordered_map<int, int> unordered;
std::set<int> keys;
for (auto& it : unordered) keys.insert(it.first);
for (auto& it : keys) {
    std::cout << unordered[it] << ' ';
}

您可以使用向量來存儲您的鍵值對,然后將它們排序在向量中,最后將它們放回 map。

#include <iostream>                                 
#include <unordered_map>                                 
#include <algorithm>                                 
#include <vector>                                 

using namespace std;                                

int main(){                                
    unordered_map<string, int> sdict = {{"hello", 11 }, {"world", 52}, {"tommy", 3}};               
    unordered_map<string, int> resdict;          

    vector<pair<string, int>> tmp;
    for (auto& i : sdict)                                         
        tmp.push_back(i);                                

    for (auto& i : sdict)       
        cout <<  i.first << " => " << i.second << endl;  

    // sort with descending order.
    sort(tmp.begin(), tmp.end(),                                   
    [&](pair<string, int>& a, pair<string, int>& b) { return a.second < b.second; });

    for (auto& i : tmp)                          
    {                           
        resdict[i.first] = i.second;                   
    }                                

    cout << "After sort." << endl;   
    for (auto& i : resdict)     
        cout <<  i.first << " => " << i.second << endl;           
    return 0;                                              

}                                            

使用以下命令編譯。

g++ --std=c++11 test_sort_ordered_map.cpp

結果是:

tommy => 3
hello => 11
world => 52
After sort.
world => 52
hello => 11
tommy => 3

暫無
暫無

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

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