我有这样一个类:
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/