当使用
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<std::pair<int,int>, int>
被编译通过的原因是,
std::pair
定义了
operator<
用于对键排序,而
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>
是一种不好的编码习惯。为什么呢?请看这里。