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

Lud*_*ven 6 c++ unordered-map c++-standard-library c++11 std-pair

#include <bits/stdc++.h>

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

int main()
{
    mp[make_pair(1, 2)]++;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我怎样才能让它工作std::unorderd_m

JeJ*_*eJo 4

当对 执行相同操作时std::map,不会发生错误。为什么?我怎样才能让它工作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;
Run Code Online (Sandbox Code Playgroud)

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

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
Run Code Online (Sandbox Code Playgroud)

std::map<std::pair<int,int>, int>编译的原因是,定义了并使用它对其键进行排序,而 的哈希函数尚未定义,因此需要一个将元素保存在其存储桶中。这个你需要定义。operator< std::pairstd::mapstd::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;
}
Run Code Online (Sandbox Code Playgroud)

PS#include <bits/stdc++.h>这是一种不好的编码习惯。为什么?看到这个

  • *If* 模板,我建议使用两个模板参数,以便您可以计算 `std::pair&lt;int, double&gt;` 或类似的哈希值...... (2认同)