gpt4 book ai didi

c++ - 在 hashmap/unordered_map 中,当 value 已经包含 key 时,是否可以避免数据重复

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:06 24 4
gpt4 key购买 nike

给定以下代码:

struct Item
{
std::string name;
int someInt;
string someString;
Item(const std::string& aName):name(aName){}
};
std::unordered_map<std::string, Item*> items;
Item* item = new Item("testitem");
items.insert(make_pair(item.name, item);

项目名称将在内存中存储两次 - 一次作为项目结构的一部分,一次作为 map 条目的键。是否可以避免重复?对于大约 100M 的记录,这种开销变得巨大。

注意:我需要在 Item 结构中包含名称,因为我使用 hashmap 作为另一个 Item-s 容器的索引,并且我无法访问该映射的键值。

最佳答案

好吧,既然你说你是用指针作为值,那我就把我的答案复活。

有点hacky,但应该可以。基本上你使用指针和自定义哈希函数

struct Item
{
std::string name;
int someInt;
string someString;
Item(const std::string& aName):name(aName){}

struct name_hash
{
size_t operator() (std::string* name)
{
std::hash<std::string> h;
return h(*name);
}
};
};
std::unordered_map<std::string*, Item*, Item::name_hash> items;
Item* item = new Item ("testitem");
items.insert(make_pair(&(item->name), item);

关于c++ - 在 hashmap/unordered_map 中,当 value 已经包含 key 时,是否可以避免数据重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13622501/

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