将指针视为unsigned int for hash

Pil*_*pel 3 c++

我想为我的自定义类型AnimationSet重载std :: hash模板:

struct AnimationSet {
    const AnimationData *animationData;
    SceneNode *sceneNode;

    bool operator==(const AnimationSet &other) const {
        return ( this->animationData == other.animationData &&
                 this->sceneNode == other.sceneNode );
    }
};
Run Code Online (Sandbox Code Playgroud)

如您所见,它是一个只包含两个指针的结构.

将这些指针强制转换为unsigned int以计算AnimationSet的哈希值是否合法?

namespace std {
    template<>
    struct hash<AnimationSet> {
        size_t operator()(const AnimationSet &set) const {
            hash<unsigned int> h;

            return h((unsigned int)set.animationData) ^ h((unsigned int)set.sceneNode);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

编辑:我在哈希重载的上下文中问这个问题,但我想知道更一般的问题的答案:"将任何指针转换为unsigned int是否公平?"

Jon*_*ely 8

通常,不,指针的大小不一定与unsigned int.特别是,在大多数64位系统上,它们将是两倍大,因此您所要做的就是使用指针的最低32位,这更有可能导致冲突(特别是因为许多指针不会有设置的最低两位,因此您只获得有助于哈希值的30位有用信息.

你应该#include <cstdint>std::uintptr_t下去.这是一个无符号整数类型,保证能够存储指针的值而不会丢失任何位.