gpt4 book ai didi

c++ - 关于 std::unordered_multimap 中键唯一性的保证

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:57 25 4
gpt4 key购买 nike

我想知道 std::unordered_multimap 中关键对象的唯一性在处理迭代时。

我将尝试解释这一点:我需要将一些数据与 map 中的键类型相关联,这些数据不应在Hash 中考虑。或 KeyEqual元素,但我需要它来避免与其存储单独的 map (出于优化目的)。

所以与我的想法相关的代码如下:

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> 的第一个元素。映射到单个元素总是相同的。作为pairconst Key听起来 map 中的每个元素都有其键值拷贝,所以如果我这样做

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;

这允许我将属性与键配对,但由于它需要使用两级迭代器,所以一切都不那么干净。

还有其他我没有看到的解决方案吗?

最佳答案

23.5.5.1 Class template unordered_multimap overview [unord.multimap.overview]

1 An unordered_multimap is an unordered associative container that supports equivalent keys (an instance ofunordered_multimap may contain multiple copies of each key value) and that associates values of anothertype mapped_type with the keys. The unordered_multimap class supports forward iterators.

unordered_multimap可能包含 key 的多个拷贝,如果您想要 key 的单个拷贝,则可能是 unordered_map<K, vector<V>>可能更合适。

关于c++ - 关于 std::unordered_multimap 中键唯一性的保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com