插入unordered_map<pair<int,int>, int> 抛出编译器错误

Inserting into unordered_map<pair<int,int>, int> throwing compiler errors

本文关键字:int lt gt 错误 编译器 pair unordered map 插入      更新时间:2023-10-16

以下代码在语义上有什么问题吗?

#include<iostream>
#include<unordered_map>
using namespace std;
int main()
{
  unordered_map<pair<int,int>, int> M;  // <--- many compiler errors here
  pair<int,int> p = make_pair(5,4);
  M[p] = 3;
}

我遇到了一堆编译器错误,但对我来说,它似乎应该可以正常工作(如果我只使用 int 作为unordered_map的键,它就会起作用)。知道为什么会这样吗?

您在以下行收到很多编译器错误:

unordered_map<pair<int,int>, int> M;

这是因为您将pair<int, int>定义为unordered_map的键,并且没有pair<int, int>的隐式hash(尽管存在operator==)。
即使您将一些虚拟class X作为其密钥,也会发生此类错误,如果它没有 hash 和/或operator== .

一般来说,在声明unordered_map的键时,应该可以通过"键"访问以下函数:

template <class Key,
          class T,
          class Hash = hash<Key>,  // implement if missing
          class Pred = equal_to<Key>,  // implement if missing
          class Alloc = allocator<pair<const Key,T>>
          >
class unordered_map;

int的情况下,默认的hash&operator==意味着;因此没有错误。