如何将 C unordered_set 用于自定义类?

新手上路,请多包涵

如何将类的对象存储在 unordered_set 中?我的程序需要经常检查 unordered_set 中是否存在对象,如果存在,则对该对象进行一些更新。

我在网上查阅了如何使用 unordered_set ,但遗憾的是大多数教程都是关于在 intstring 类型上使用它。但是我怎样才能在课堂上使用它呢?如何定义散列函数以使以下示例中的 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 许可协议

阅读 775
1 个回答

由于这是 C++ unordered_set of objects 在 Stack Overflow 上的最高 Google 结果,我将发布一个简单但完全说明性并复制/粘贴可运行的示例:

 // 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;
}

原文由 cdahms 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题