C++ 中的 HashCodeBuilder
如果我想在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 boost::hash_combine。
Use boost::hash_combine.
顺便说一下,hashCode 方法不返回对象的标识符。这是一个常见的误解。没有什么可以阻止同一类的 2 个对象返回相同的值。 hashCode 用于哈希表数据结构,而不是用于标识对象。这是两个不同的概念。
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.