Ale*_*lev 5 c++ stl unordered-map hashmap
给出以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
项目名称将存储在内存中两次 - 一次作为Item结构的一部分,一次作为映射条目的键.是否有可能避免重复?有了大约100M的记录,这个开销变得很大.
注意:我需要在Item结构中有名称,因为我使用hashmap作为Item-s的另一个容器的索引,并且我无法访问map的键值.
小智 4
好吧,既然你说你正在使用指针作为值,我特此将我的答案带回来。
有点 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |