【问题标题】:Putting a vector of pairs in an unordered_map vs a map [duplicate]将一对向量放入 unordered_map 与地图 [重复]
【发布时间】:2020-02-27 13:27:49
【问题描述】:

所以考虑一下这段代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<vector<pair<int,int>>,int> mp ;
    for(int i=0;i<10;i++)
    {
        vector<pair<int,int>> v ;
        for(int j=0;j<10;j++)
            v.push_back(make_pair(j,2*j)) ;
        mp[v] = i ;

    }
    return 0;
}

我在这里所做的是创建一个unordered_map,其键类型为vector&lt;pair&lt;int,int&gt;&gt;。如您所见here,这会引发错误。

但是当我将这个 unordered_map 更改为 mapthis error doesn't occur anymore 时。 那就是:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    map<vector<pair<int,int>>,int> mp ;
    for(int i=0;i<10;i++)
    {
        vector<pair<int,int>> v ;
        for(int j=0;j<10;j++)
            v.push_back(make_pair(j,2*j)) ;
        mp[v] = i ;

    }
    return 0;
}

效果很好。

那么unordered_maps 并将vectors 作为键放入其中是什么意思?这是怎么回事?

【问题讨论】:

  • 85:34: error: no match for call to ‘(const std::hash&lt;std::vector&lt;std::pair&lt;int, int&gt; &gt; &gt;) (const std::vector&lt;std::pair&lt;int, int&gt; &gt;&amp;)这个错误信息还不够清楚吗?只需阅读关键类的要求有mapunordered_map
  • 这可能会有所帮助:thispointer.com/…。 map 和 unordered map 的区别在于内部处理键的方式。从日志看来,关键向量> 的散列函数似乎丢失了。
  • 你到底为什么要使用整数对的向量作为键?
  • map 正在使用运算符&lt; 为向量定义排序。 unordered_map 需要一个哈希值才能将密钥放入适当的存储桶中,但由于您没有指定它,所以它会引发错误。
  • 不相关,但可能对未来有所帮助:Why should I not #include<bist/stdc++.h>Why is “using namespace std;” considered bad practice?。也请直接在问题中发布错误消息以节省我们一些时间。

标签: c++ hashmap unordered-map


【解决方案1】:

详细说明一下: 对于std::map

std::map 是一个排序的关联容器,它包含具有唯一键的键值对。键通过使用比较函数比较进行排序。 [...] 地图通常实现为红黑树。

“函数比较”是一个模板参数,默认值为std::less&lt;Key&gt;。因此,地图需要使用&lt; 比较值以将它们排序到红黑树中。 std::vector支持(这样的比较)[https://en.cppreference.com/w/cpp/container/vector/operator_cmp].

std::unoredered_map 在另一个哈希上需要一个哈希函数来将键放入哈希桶中。使用的哈希函数是一个模板参数,默认值为std::hash&lt;Key&gt;

std::hash 只有vector&lt;bool&gt; 的重载,而不是任何通用向量。除非您提供自定义哈希函数,否则 unordered_map 无法计算键的哈希值,这也是错误消息告诉您的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2013-01-30
    • 2020-11-15
    相关资源
    最近更新 更多