C++ 中的 HashCodeBuilder

发布于 2024-08-02 17:01:25 字数 616 浏览 2 评论 0原文

如果我想在 Java 中为给定对象生成哈希,我知道的最简单的方法是使用 Apache Commons HashCodeBuilder

public class Person {
   String name;
   int age;
   boolean smoker;
   ...

   public int hashCode() {
     // you pick a hard-coded, randomly chosen, non-zero, odd number
     // ideally different for each class
     return new HashCodeBuilder(17, 37).
       append(name).
       append(age).
       append(smoker).
       toHashCode();
   }
 }

C++中有类似的东西吗?

If I want generate a hash for a given object in Java, the easiest way I know is to use the Apache Commons HashCodeBuilder:

public class Person {
   String name;
   int age;
   boolean smoker;
   ...

   public int hashCode() {
     // you pick a hard-coded, randomly chosen, non-zero, odd number
     // ideally different for each class
     return new HashCodeBuilder(17, 37).
       append(name).
       append(age).
       append(smoker).
       toHashCode();
   }
 }

Is there anything similar in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

救星 2024-08-09 17:01:25

By the way, the hashCode method does not return an identifier for an object. This is a common misconception. There is nothing to prevent 2 objects of the same class returning the same value. The hashCode is meant for hash table data structures, not for identifying objects. Those are 2 separate concepts.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文