将成对向量放入 unordered_map 与地图

Putting a vector of pairs in an unordered_map vs a map

所以考虑这个代码:

#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;
}

我在这里所做的是使用 vector<pair<int,int>> 类型的键创建一个 unordered_map。如您所见 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 作为键放入其中是什么?这是怎么回事?

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

std::map is a sorted associative container that contains key-value pairs with unique keys.Keys are sorted by using the comparison function Compare. [...] Maps are usually implemented as red-black trees.

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

std::unordered_map 在另一个哈希上需要一个哈希函数来将键放入哈希桶中。使用的哈希函数是模板参数,默认值为std::hash<Key>.

std::hash 仅对 vector<bool> 有重载,对任何通用向量都没有。除非您提供自定义哈希函数,否则 unordered_map 无法计算键的哈希值,这也是错误消息告诉您的内容。