2016-06-09 20 views
6

我在處理迭代時想知道std::unordered_multimap中關鍵對象的唯一性。我試圖解釋一下:我需要將一些數據與地圖中的鍵類型關聯起來,這些數據不應該在HashKeyEqual元素中考慮,但我需要它來避免存儲單獨的地圖它(爲了優化目的)。關於std :: unordered_multimap中關鍵唯一性的保證

因此,與我的想法相關的代碼如下:

struct Key { 
    void* data; 
    mutable bool attribute; 

    Key(void* data) : data(data), attribute(false) { } 
    bool operator==(const Key& other) const { 
    return data == other.data; 
    } 
}; 

struct KeyHash { 
    size_t operator()(const Key& key) const { 
    return std::hash<void*>()(key.data); 
    } 
}; 

class Foo { 
public: 
    int i; 
    Foo(int i) : i(i) { } 
}; 

std::unordered_multimap<Key, Foo, KeyHash> map; 

問題的事實,雖然這工作得很好,沒有任何有關的關鍵檢索爲第一要素的事實擔保發生映射到單個元素的std::pair<const Key, Foo>始終是相同的。作爲const Keypair這聽起來像在地圖上的每一個元素都有其通過值的密鑰副本,這樣,如果我做

void* target = new int(); 
map.emplace(std::make_pair(target, Foo(1))); 
map.emplace(std::make_pair(target, Foo(2))); 


auto pit = map.equal_range(target); 
pit.first->first.attribute = true; 
std::cout << std::boolalpha << (++pit.first)->first.attribute << endl; 

這就產生false這確認了我的心思。因此,如果您有多個具有相同密鑰的值(因爲您使用的是std::unordered_map,所以這是您想要的),所以浪費很多空間來存儲密鑰。

我沒有看到任何其他的解決辦法,而不是像

struct Value 
{ 
    std::vector<Foo> foos; 
    bool attribute; 
}; 

std::unordered_map<void*, Value> map; 

,讓我配對的屬性與關鍵,但讓一切不乾淨的,因爲它需要與迭代器的兩個層面的工作。

我還沒有看到其他解決方案嗎?

+0

只需使用'boost :: multiindex' – Slava

+2

'map [target] = Foo(1);''std :: unordered_multimap'不會超載'operator []' –

+0

您的要求並不十分清楚。你是否在尋找像'std :: unordered_map >'這樣的東西?這將愉快地將多個值與相同的密鑰相關聯,而不會複製密鑰。 –

回答

2

23.5.5.1類模板unordered_multimap概述[unord.multimap.overview]

1所述的unordered_multimap是支持等價密鑰( unordered_multimap的一個實例可以包含每個鍵值的多個副本的無序關聯容器),並且將另一個 類型mapped_type的值與關鍵字相關聯。 unordered_multimap類支持前向迭代器。

一個unordered_multimap可能含有關鍵的多個副本,如果你想關鍵的一個副本,然後一個潛在的unordered_map<K, vector<V>>可能更合適。