c++ - 我的哈希键类型和函数有什么问题?

标签 c++ hash unordered-map

我正在尝试为一个类编写自己的哈希函数,该类本质上是无符号整数的包装器。我一直在尝试关注这个话题 here : 和这个资源 here .为什么这不起作用?请参阅代码注释以了解错误。

struct Entity
{
    unsigned int id;

    bool operator==( const Entity &other ) const
    {
        return ( id == other.id );
    }
};

template<struct T>
class EntityHash;

template<>
class EntityHash<Entity> // Error: Type name is not allowed
{
public:
    std::size_t operator()( const Entity& entity ) const
    {
        size_t h1 = std::hash<unsigned int>()( entity.id );
        return h1; // Also... do I need a << 1 at the end of this to bitshift even though I'm not combining?
    }
};

// Elsewhere
std::unordered_map<Entity, unsigned int, EntityHash> map; // Error: Argument list for class template EntityHash is missing

最佳答案

template <struct T>
class EntityHash;

可能不是您想要的。使用 template <class T>template <typename T> .

unordered_map 的第三个模板参数必须是类型,而不是模板的名称。所以:

std::unordered_map<Entity, unsigned int, EntityHash<Entity>> map;

关于c++ - 我的哈希键类型和函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33249055/

相关文章:

c++ - 海湾合作委员会 4.1.2 : error: integer constant is too large for ‘long’ type

hash - MD5 哈希值中只能包含数字或只能包含字母吗?

c++ - 如何以 O(1) 的时间从 C++ 哈希表中随机检索元素

c++ - 将 cuda 推力与数组一起使用而不是 vector 到 inclusive_scan

c++ - 在 UE4 中使用 C++ 将资源从内容加载到场景

c++ - 将对象插入 C++ 顺序列表

c++ - std::unordered_map 如何确定哈希表中特定键的位置?

c++ - 线程 C++ 的 lambda 内部函数调用

go - Bcrypt 为相同的密码生成不同的散列

c++ - 插入在 Unordered_map (C++) 中花费很长时间,以 ULONG 为键且桶数未知