为什么这个 unordered_map 找不到现有密钥? (C++14)

Why is this unordered_map not finding existing keys? (C++14)

我正在尝试使用 unordered_map 作为自定义类型。但是,映射存储重复的条目,它们具有相同的散列值,应该 在使用 == 时评估为相等。

我已将我的代码缩减为以下概念证明,我可以在其中看到哈希函数正确运行,但从未调用过等于运算符。

#include <unordered_map>

// Define a class with a single integer member.
class Example
{
  public: int x;
  public: Example(int x)
  {
    this->x = x;
  }

  // Overload == and compare the single member.
  public: bool operator==(const Example &other) const
  {
    std::cout << "Comparing two objects\n";
    return this->x == other.x;
  }
};

// Define a hash function class
class ExampleHash
{
  public: size_t operator()(const Example* key) const
  {
    // simply return the member variable as the hash value.
    std::cout << "Returning hash value " << key->x << "\n";
    return key->x;
  }
};

int main()
{
  // Create an empty map.
  std::unordered_map<Example*, int, ExampleHash> m;

  std::cout << "Inserting a new key\n";      

  // Insert an object with the value 1.
  m[new Example(1)] = 1;

  std::cout << "Existing hashes:\n";
  ExampleHash fn;
  for (auto const &item : m) {
    size_t h = fn(item.first);
    std::cout << "  " << h << ", ";
  }
  std::cout << "\n";

  std::cout << "Finding the key\n";

  // Check if the object is in the map.
  std::cout << ((m.find(new Example(1)) != m.end()) ? "Found" : "Not found") << "\n";
}

输出:

Inserting a new key
Returning hash value 1
Existing hashes:
Returning hash value 1
  1, 
Finding the key
Returning hash value 1
Not found

(请注意,调用 unordered_map::find 时没有“比较两个对象”行,尽管哈希值显然已经在映射中。)

指针不是它们指向的对象。

您正在使用指针作为键。对象等于运算符将被忽略。