c++使用无序键组合进行映射查找
C++ using an unordered key combination for a map lookup
我想创建一个unordered_map
,其中键是两个整数的组合。由于键值的顺序在比较时将被忽略,因此我考虑使用unordered_set
作为键,如下所示:
#include <unordered_set>
#include <unordered_map>
using namespace std;
int main ()
{
unordered_set<int> key_set1 = {21, 42};
unordered_map<unordered_set<int>, char> map;
map[key_set1] = 'a';
...
unordered_set<int> key_set2 = {42, 21};
if(map[key_set2] == map[key_set2])
success();
}
在编译时,它看起来像是哈希函数的一些问题:
error: no match for call to ‘(const std::hash<std::unordered_set<int> >) (const std::unordered_set<int>&)’
noexcept(declval<const _Hash&>()(declval<const _Key&>()))>
我该如何解决这个问题?还是有更好的方法/数据结构?
没有预定义的散列函数为unordered_set
,所以你必须实现自己的;这里有相关的文档http://en.cppreference.com/w/cpp/utility/hash.
基本上你需要:
// custom specialization of std::hash can be injected in namespace std
namespace std
{
template<> struct hash<unordered_set<int>>
{
std::size_t operator()(unordered_set<int> const& s) const
{
std::size_t hash = 0;
for (auto && i : s) hash ^= std::hash<int>()(i);
return hash;
}
};
}
现在xor
不是推荐的组合哈希函数的方法,但它应该在这种情况下工作,因为它既无序和集合。因为它是无序的你需要一个可交换的函数。推荐的散列组合器没有此属性,因为您通常希望"abc"的散列方式与"bca"不同。其次,它是一个集合的事实保证了你不会有任何重复的元素。这可以避免您的哈希函数因为x ^ x == 0
.
我还应该提到,您希望在cpp文件中定义它,这样您就不会将std类型上的特定哈希实现暴露给所有人。
问题是unordered_set不是为在无序容器中用作键而构建的。
如果总是恰好使用两个整型数,那么使用一对整型数作为键,并添加一个函数将两个整型数组成一个正确排序的整数对,这样会更经济:
pair<int,int> unordered_key(int a, int b) {
return a<b?make_pair(a, b):make_pair(b, a);
}
如前所述,要直接使用std::pair
作为键,您需要显式地为它定义一个哈希函数。如果你想避免这种情况,你可以把2个无符号整数按位组合成1:
uint64_t makeKey(uint32_t a, uint32_t b)
{
return a < b ? (static_cast<uint64_t>(a) << 32) + b : (static_cast<uint64_t>(b) << 32) + a;
}
int main ()
{
auto key_set1 = makeKey(21, 42);
unordered_map<uint64_t, char> map;
map[key_set1] = 'a';
//...
auto key_set2 = makeKey(42, 21);
if(map[key_set1] == map[key_set2])
std::cout << "success" << std::endl;
}
由于顺序在这里并不重要,您可以使用std::pair
和自定义工厂来强制两个整数的顺序:
std::pair<int, int> make_my_pair(int x, int y) {
return std::make_pair(std::min(x, y), std::max(x, y));
}
当然,这只会在你一直使用make_my_pair
的情况下才会起作用。
或者,您可以定义自己的具有类似属性的键类。
相关文章:
- 如何在多映射的字符串中查找子字符串
- 由并发无序映射查找线程调用的函数是否安全?
- if else VS映射查找
- std::使用迭代器映射查找距离,程序不会终止
- 将长位数组映射到查找表
- C++ 映射查找值和关联的键
- c 映射::查找或映射:: iterator,它是更有效的W.R.T复杂性
- 性能映射 C++ 查找(G++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3))
- 如何遍历 STL 映射(查找所有可能的对)
- 使用映射 c++ 查找矢量的多种模式
- 映射查找函数调用 Vs 将查找缓存为静态变量
- C++多映射查找失败
- 如何优化无序映射查找
- C++ 映射查找找不到特定键
- STL哈希表[无序映射]查找性能与大小
- 使用映射查找具有给定和(带有负数)的子数组
- TBB 并发哈希映射查找和插入
- 定时矢量与映射与未定义映射查找
- c++使用无序键组合进行映射查找
- STL映射查找第一个不可重复的字符