加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将指针视为unsigned int for hash

发布时间:2020-12-16 10:11:46 所属栏目:百科 来源:网络整理
导读:我想为我的自定义类型AnimationSet重载std :: hash模板: struct AnimationSet { const AnimationData *animationData; SceneNode *sceneNode; bool operator==(const AnimationSet other) const { return ( this-animationData == other.animationData this
我想为我的自定义类型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 );
    }
};

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

将这些指针强制转换为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);
        }
    };
}

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读