c++ - 我可以使用成员变量作为 hash_set/hash_map 的键吗?

标签 c++ hash hashmap

我有这样一个类:

class Foo
{
   long long Id;
   string x;
   string y;
   // other member variables and functions
};

我想将其存储在 hash_set 中(或 hash_map ),但使用 Id 成员变量作为插入和搜索的键。我不确定我该怎么做。我想到了以下几种方法,但都不是很好:

1) 我可以编写一个自定义散列函数,使用 Id 对对象进行散列,但我不能使用 find() hash_set 上的方法通过 Id ( long long ) 查找项目,因为它需要 Foo要传入的对象。

2) 我可以复制 Id 并创建一个 hash_map<long long, Foo>而不是 hash_set<long long, Foo>但我有 1 亿个这些对象的实例,所以我不想复制 Id 字段。

3) 我可以将 Id 字段移到 Foo 之外然后做 hash_map<long long, Foo> , 但它会有点困惑,因为 Id 由类在内部使用,最好将它与 Foo 一起保存.

有什么想法吗?我正在寻找的是一种存储方式 Foo对象,但能够在 hash_set 中搜索它们使用 long long (按 ID)。

谢谢!

最佳答案

1) I can write a custom hash function that will hash the object using the Id, but then I can't use the find() method on hash_set to lookup the item by Id (long long) since it will require a Foo object to be passed-in.

这是标准 map 和集合容器的常见问题。添加创建比较对象的构造函数或静态成员,一个只有关键成员有效的对象。

关于c++ - 我可以使用成员变量作为 hash_set/hash_map 的键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3908641/

相关文章:

c++ - 如果enable_if确定T是一个容器,则启用一个结构体?

php - 安全问题的答案应该散列吗?

java - 如何使用 freemarker 分割 hashmap 的值?

c++ - 对自身的不明确函数调用

c++ - 获取 int 而不是 float

java - Java中广泛使用的哈希算法用于实现哈希表?

c++ - 哈希类哈希

java - 清除 HashMap 中 List 类型的值

java - 这里不需要方法引用表达式,编译时错误

c++ - 本地数组的性能和安全性作为参数