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

标签 c++ unordered-set hash-function

如何在 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;
}

最佳答案

由于这是 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/

相关文章:

存储任意引用的 C++ 包装类,但它本身不是类模板

c++ - C++中指针数组中的const限定符

c++ - 为什么在运算符重载中允许返回构造函数?

c++ - std::unordered_set::load_factor,为什么是 float 而不是 double?

java - 具有最小冲突的两个整数数组的哈希函数

c++ - 顶级 qml 文件中的 Repeater 元素导致 QtQuick 1.1 (QtCreator 3.5.1) 中的绑定(bind)循环

c++ - 如何覆盖类内定义的枚举的 std::hash?

c++ - 无法分配给 const 成员函数中的非静态数据成员

hashtable - 编程语言用于字典/关联数组的默认哈希函数是什么?

c++ - unordered_map 的哈希函数是确定性的吗?