【发布时间】:2013-11-15 16:15:42
【问题描述】:
我有一个应该很有趣的问题。我想在构造时“转发初始化”std::unordered_map 中的一个项目。
这些是细节。我有一个从std::string 到自定义类prop 的哈希映射,在我的梦中,它会初始化一个成员变量,计算字符串传递给 std::unordered_map::operator[] 的哈希。 p>
这是我编写的一个方便的代码,但我不知道从哪里开始。
为什么会这样?因为我想避免类似“如果字符串不在容器中计算哈希;用prop 做事”。避免这种if 可能会影响我的表现。因此,当地图在容器中添加新项目时,构造函数以及散列将只执行一次。会很棒的。
有什么提示吗?
感谢和干杯!
#include <iostream>
#include <string>
#include <unordered_map>
class prop
{
public:
prop(std::string s = "") : s_(s), hash_(std::hash<std::string>()(s))
{
// Automagically forwarding the string in the unordered_map...
};
std::string s_;
std::size_t hash_;
int x;
};
int main(int argc, const char * argv[])
{
// Forward the std::string to the prop constructor... but how?
std::unordered_map<std::string, prop> map;
map["ABC"].x = 1;
map["DEF"].x = 2;
map["GHI"].x = 3;
map["GHI"].x = 9; // This should not call the constructor: the hash is there already
std::cout << map["ABC"].x << " : " << map["ABC"].s_ << " : " << map["ABC"].hash_ << std::endl;
std::cout << map["DEF"].x << " : " << map["DEF"].s_ << " : " << map["DEF"].hash_ << std::endl;
std::cout << map["GHI"].x << " : " << map["GHI"].s_ << " : " << map["GHI"].hash_ << std::endl;
std::cout << map["XXX"].x << " : " << map["XXX"].s_ << " : " << map["XXX"].hash_ << std::endl;
return 0;
}
【问题讨论】:
-
为什么不将
prop存储在std::unordered_set中,并使用适当的hash和相等操作? -
我可以更换容器,但是如何避免使用讨厌的
if?这不仅仅是我需要该哈希的相等性。在一个实际的类中,我将存储从给定字符串计算的K哈希值。 -
我想你应该看看 C++14 即将推出的特性,比如基于不同值查找元素。请参阅 C++14 的 std::unordered_set::find。
标签: c++ c++11 hashmap initialization unordered-map