unordered_map没有散列

时间:2013-12-08 19:32:54

标签: c++ map stl

我想使用一个像std :: map一样的结构,但没有排序,我不需要订购,我的密钥非常大,所以它“小于”比较需要时间。 所以,我看到了unordered_map,但它有一个哈希模板参数,那么,如何使用unordered_map而不进行哈希?我真的需要建立自己的容器吗?

此问题也适用于std :: set。

修改 有些答案建议创建我自己的哈希,但我不能这样做,我应该在这里指定它。密钥包含浮点数据,因此散列它将是一个真正的坏主意。我需要直接比较(std :: equal_to)。

2 个答案:

答案 0 :(得分:1)

创建自己的哈希,可以通过在密钥字段上组合std::hash的重载来轻松完成。

cppreference example(与之前的链接相同)非常好(即使您不需要模板内容):

struct S
{
    std::string first_name;
    std::string last_name;
}; 

template <class T>
class MyHash;

template<>
class MyHash<S>
{
public:
    std::size_t operator()(S const& s) const 
    {
        std::size_t h1 = std::hash<std::string>()(s.first_name);
        std::size_t h2 = std::hash<std::string>()(s.last_name);
        return h1 ^ (h2 << 1);
    }
};

之后,您可以在std::unorderd_map

中使用它
std::unordered_map<S, Value, MyHash<S>> the_map;

顺便说一句std::unordered_set也需要哈希。

答案 1 :(得分:0)

在声明unordered_map之前,您需要为密钥设计哈希对象。

    namespace std
    {
    template <>
    class hash<Key>
    {
    public:
      size_t operator()(const Key &) const
      {
        // ... your hash function for Key object ...

      }
    };
    }

    std::unordered_map<Key, Value> myMap;

示例,如果我希望您用作密钥对:

    namespace std
    {
    class hash<pair<string, int>>
    {
    public:
      size_t operator()(const pair<string, int> &s) const
      {
        size_t h1 = hash<string>()(s.first);
        size_t h2 = hash<int>()(s.second);
        return h1 ^ (h2 << 1);
      }
    };
    }

    unordered_map<pair<string, int>, string> myMap;