【问题标题】:Why can not I use operator[] for std::unordered_map<std::pair<int,int>, int> but for same key-value pair of `std::map`? [duplicate]为什么我不能将 operator[] 用于 std::unordered_map<std::pair<int,int>, int> 但用于 `std::map` 的相同键值对? [复制]
【发布时间】:2018-08-25 07:06:10
【问题描述】:
#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一起工作?

【问题讨论】:

  • 你用的c++是什么版本的?
  • 我在 G++11 和 G++17 上都试过了,结果一样

标签: c++ c++11 unordered-map c++-standard-library std-pair


【解决方案1】:

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;

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&lt;std::pair&lt;int,int&gt;, int&gt; 被编译的原因是,operator&lt; std::pairstd::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 &lt;bits/stdc++.h&gt;是一种糟糕的编码习惯。为什么?见this

【讨论】:

  • If 模板,我建议您使用两个模板参数,这样您就可以计算 std::pair&lt;int, double&gt; 或类似的哈希值...
  • @Aconcagua 真的。让我编辑。但是,OP 只有ints,这意味着根本不需要模板。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 2011-10-29
  • 2021-11-18
相关资源
最近更新 更多