映射v.s.unordered_map中可允许的密钥类型
Admissible type of key in map v.s. unordered_map
我知道unordered_map<T, int>
在从键O(1(检索值时比map<T, int>
在性能方面更高效。
然而,我发现unordered_map<T, int>
支持的类型不如map<T, int>
那么多。
例如,map<pair<int, int>, int>
可以,但unordered_map<pair<int, int>, int>
不可以。
我想知道这其中有什么潜在的困难吗?如果考虑性能,我可以使用什么数据结构来获得具有O(1(性能的密钥类型对的哈希表。
您可以定义一个自定义哈希函数:
#include <unordered_map>
typedef std::pair<int,int> int_pair;
class MyHashFunc {
std::hash<int> int_hash_func;
public:
long operator()(const int_pair &k) const{
return (int_hash_func(k.first) << 16) + (int_hash_func(k.second));
}
};
int main() {
std::unordered_map<int_pair, int, MyHashFunc> m;
return 0;
}
它之所以不能开箱即用,是因为类型pair<T,T>
没有定义哈希函数,而unordered_map
本质上是一个哈希映射,所以它的键必须是可哈希的。
关于unordered_map<pair<int, int>, int>
没有根本问题。问题是,您需要提供哈希函数和比较函数<pair,pair>
的具体情况,请参阅此问题作为关键,关于一般情况的更多详细信息,请参阅本答案。
如果您可以提供一种从pair<int, int>
生成哈希的方法,那么您就可以使用它。
示例:
#include <unordered_map>
#include <utility>
using namespace std;
struct IntPairHash
{
size_t operator()(pair<int, int> const& p)
{
// If you have a 64 bit platform where sizeof(size_t) == 64
// and sizeof(int) == 32, you can use:
size_t h = p.second;
h <<= 32;
h += p.first;
return h;
// For other platforms, a more different approach to come up with
// a hash value for p must be devised.
}
};
void foo()
{
unordered_map<pair<int, int>, int, IntPairHash> a;
}
相关文章:
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 允许从 std::map 的密钥窃取资源?
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 在没有密钥的情况下读取密文的剩余噪声预算
- 如何修复无效的API密钥,IP或操作权限错误?
- 所有可能的链接生成器与64位密钥
- 如何在unordered_map中更改密钥?
- 获取当前密钥状态?
- curl_easy_perform() 失败:SSL 对等证书或 SSH 远程密钥不正常
- 将密钥发送到非前台的游戏窗口
- 重载std::映射不同的密钥类型
- C 11多态映射键静态断言失败:哈希函数必须与密钥类型的参数无关
- 具有可比的密钥类型的地图
- 如何使用std :: vector作为c 中std :: unordered_map的密钥类型
- std::unordered_map:渐近{search,insert,remove}性能取决于密钥的大小和数据类型
- std::unordered_map::查找使用与密钥类型不同的类型
- 具有自定义密钥类型的STL无序映射
- 映射v.s.unordered_map中可允许的密钥类型
- C++ STL 错误的密钥类型
- 如何为多个密钥类型专门化std映射