如何将类的对象存储在 unordered_set
中?我的程序需要经常检查 unordered_set
中是否存在对象,如果存在,则对该对象进行一些更新。
我在网上查阅了如何使用 unordered_set
,但遗憾的是大多数教程都是关于在 int
或 string
类型上使用它。但是我怎样才能在课堂上使用它呢?如何定义散列函数以使以下示例中的 node_id
成为 unordered_set
的键?
#include <iostream>
#include <unordered_set>
using namespace std;
// How can I define a hash function that makes 'node' use 'node_id' as key?
struct node
{
string node_id;
double value;
node(string id, double val) : node_id(id), value(val) {}
};
int main()
{
unordered_set<node> set;
set.insert(node("1001", 100));
if(set.find("1001") != set.end()) cout << "1001 found" << endl;
}
原文由 daydayup 发布,翻译遵循 CC BY-SA 4.0 许可协议
由于这是
C++ unordered_set of objects
在 Stack Overflow 上的最高 Google 结果,我将发布一个简单但完全说明性并复制/粘贴可运行的示例: