我有一个应该很有趣的问题。我想在“正在初始化”施工时在std::unordered_map
中的一个项目。在地图上优化初始化:转发密钥
这些是细节。我得从std::string
到自定义类prop
哈希地图,这在我的梦里,会初始化一个成员变量计算传递给std::unordered_map::operator[]
字符串的哈希值。
这是一个方便的代码,我已经写了,但我不知道从哪里开始。
为什么这个麻烦?因为我想避免像“如果字符串不在容器中计算哈希值;用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;
}
为什么不用''std :: unordered_set''通过适当的'hash'和equal操作存储'prop'? –
我可以更换容器,但是如何避免使用讨厌的'if'?这不仅仅是我需要这个散列的平等。在一个实际的类中,我将存储从给定字符串计算得来的'K'散列值。 – senseiwa
我想你应该看看C++ 14的即将发布的功能,例如基于不同值的元素查找。请参阅C++ 14的[std :: unordered_set :: find](http://en.cppreference.com/w/cpp/container/unordered_set/find)。 –