为什么我不能将 operator[] 用于 std::unordered_map<std::pair<int,int>, int> 而是用于 `std::map` 的相同键值对?

Why can not I use operator[] for std::unordered_map<std::pair<int,int>, int> but for same key-value pair of `std::map`?

#include <bits/stdc++.h>

std::unordered_map<std::pair<int,int>, int> mp;

int main()
{
    mp[make_pair(1, 2)]++;
}

当使用 [] operator 时,我得到这个

error: no match for ‘operator[]’ (operand types are ‘std::unordered_map<std::pair<int, int>, int>’ and ‘std::pair<int, int>’)

然而,当用std::map做同样的事情时,不会发生错误。为什么?

如何让它与 std::unorderd_m 一起使用?

when doing the same with std::map, no error occurs. why? And how can I make it works with std::unorderd_map ?

因为它们完全不同。

std::unorderd_map 元素根据其键的哈希值放置。

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,  
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;

std::map 只需要一个比较函数来对键进行排序。

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

你的 std::map<std::pair<int,int>, int> 被编译的原因是 operator< 被定义为 std::pair 并且 std::map 使用它对其键进行排序,而 std::pair 散列函数 尚未定义 因此 std::unorderd_map 需要一个保留桶中的元素。这个你需要定义。

例如,您可以按如下方式定义自定义哈希函数:

#include <unordered_map>
#include <cstddef>
#include <functional>

struct CustomHash
{
  template <typename T, typename U>
  std::size_t operator()(const std::pair<T, U> &x) const
  {
    return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
  }
};

int main()
{
    std::unordered_map<std::pair<int,int>, int, CustomHash> mp;
    mp[std::make_pair(1, 2)]++;
    return 0;
}

PS#include <bits/stdc++.h> 是一种糟糕的编码习惯。为什么?见 .