2013-11-15 28 views
0

我有一个应该很有趣的问题。我想在“正在初始化”施工时在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; 
} 
+0

为什么不用''std :: unordered_set''通过适当的'hash'和equal操作存储'prop'? –

+0

我可以更换容器,但是如何避免使用讨厌的'if'?这不仅仅是我需要这个散列的平等。在一个实际的类中,我将存储从给定字符串计算得来的'K'散列值。 – senseiwa

+0

我想你应该看看C++ 14的即将发布的功能,例如基于不同值的元素查找。请参阅C++ 14的[std :: unordered_set :: find](http://en.cppreference.com/w/cpp/container/unordered_set/find)。 –

回答

1

只需使用道具类作为重点,而不是字符串:

#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 main(int argc, const char * argv[]) 
{ 
    // Forward the std::string to the prop constructor... but how? 
    std::unordered_map<prop, int, ...> map(...); 

    prop pABC("ABC"), pDEF("DEF"), pGHI("GHI"); 

    map[pABC] = 1; 
    map[pDEF] = 2; 
    map[pGHI] = 3; 
    map[pGHI] = 9; 

    std::cout << map[pABC] << " : " << pABC.s_ << " : " << pABC.hash_ << std::endl; 
    std::cout << map[pDEF] << " : " << pDEF.s_ << " : " << pDEF.hash_ << std::endl; 
    std::cout << map[pGHI] << " : " << pGHI.s_ << " : " << pGHI.hash_ << std::endl; 

    prop pXXX("XXX"); 
    std::cout << map[pXXX] << " : " << pXXX.s_ << " : " << pXXX.hash_ << std::endl; 

    return 0; 
} 

我省略定制散列和比较功能,这个想法应该是不明确。

+0

这真的很好。除了我的数学建模。我想要一个地图'M:string - > prop',例如,你建议用它的双重'M *:prop - > string'来模拟我的问题。不容易证明,但可以接受! – senseiwa