c – 将指针视为unsigned int for hash

c – 将指针视为unsigned int for hash,第1张

概述我想为我的自定义类型AnimationSet重载std :: hash模板: struct AnimationSet { const AnimationData *animationData; SceneNode *sceneNode; bool operator==(const AnimationSet &other) const { return ( 我想为我的自定义类型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.这是一个无符号整数类型,保证能够存储指针的值而不会丢失任何位.

总结

以上是内存溢出为你收集整理的c – 将指针视为unsigned int for hash全部内容,希望文章能够帮你解决c – 将指针视为unsigned int for hash所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1218296.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存