我在處理迭代時想知道std::unordered_multimap
中關鍵對象的唯一性。我試圖解釋一下:我需要將一些數據與地圖中的鍵類型關聯起來,這些數據不應該在Hash
或KeyEqual
元素中考慮,但我需要它來避免存儲單獨的地圖它(爲了優化目的)。關於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 Key
的pair
這聽起來像在地圖上的每一個元素都有其通過值的密鑰副本,這樣,如果我做
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;
,讓我配對的屬性與關鍵,但讓一切不乾淨的,因爲它需要與迭代器的兩個層面的工作。
我還沒有看到其他解決方案嗎?
只需使用'boost :: multiindex' – Slava
'map [target] = Foo(1);''std :: unordered_multimap'不會超載'operator []' –
您的要求並不十分清楚。你是否在尋找像'std :: unordered_map>'這樣的東西?這將愉快地將多個值與相同的密鑰相關聯,而不會複製密鑰。 –