如何在 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;
}
最佳答案
由于这是 Google 在 Stack Overflow 上针对 C++ unordered_set of objects
的最高结果,我将发布一个简单但完全说明并复制/粘贴的可运行示例:
// UnorderedSetOfObjects.cpp
#include <iostream>
#include <vector>
#include <unordered_set>
struct Point
{
int x;
int y;
Point() { }
Point(int x, int y)
{
this->x = x;
this->y = y;
}
bool operator==(const Point& otherPoint) const
{
if (this->x == otherPoint.x && this->y == otherPoint.y) return true;
else return false;
}
struct HashFunction
{
size_t operator()(const Point& point) const
{
size_t xHash = std::hash<int>()(point.x);
size_t yHash = std::hash<int>()(point.y) << 1;
return xHash ^ yHash;
}
};
};
int main(void)
{
std::unordered_set<Point, Point::HashFunction> points;
points.insert(Point(1, 1));
points.insert(Point(2, 2));
points.insert(Point(1, 1)); // notice this is a duplicate with the 1st point so it won't change the set
std::cout << "points: " << "\n";
for (auto& point : points)
{
std::cout << "(" << point.x << ", " << point.y << ")" << "\n";
}
return 0;
}
关于c++ - 如何将 C++ unordered_set 用于自定义类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38554083/