unorder_map使用hash函数和关键字类型的==运算符来组织元素,使用hash函数将元素映射到桶中,为了访问一个元素,容器首先计算元素的哈希值,他指出应该搜索那个桶。默认情况下,无序容器使用关键字类型的==运算符来比较元素,它还使用一个hash<key_tpyr>类型的对象来生成每个元素的哈希值。标准库位内置类型提供了hash模板。包括string类型。但是我们不能直接定义关键类型为自定义类型的无序容器。因此我们需要自己定义该类型一个哈希函数。而且需要自己定义相等函数。
hash函数
struct HashFunc
{
std::size_t operator()(const Node &key) const
{
using std::size_t;
using std::hash;
return ((hash<int>()(key.first)
^ (hash<int>()(key.second) << 1)) >> 1)
^ (hash<int>()(key.third) << 1);
}
};相等函数
struct EqualKey
{
bool operator () (const Node &lhs, const Node &rhs) const
{
return lhs.first == rhs.first
&& lhs.second == rhs.second
&& lhs.third == rhs.third;
}
};#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
struct Node
{
int first;
int second;
int third;
Node(int i, int j, int k) :first(i), second(j), third(k)
{}
Node(){}
bool operator==(const Node&rhs) const
{
return first == rhs.first && second == rhs.second
&& third == rhs.third;
}
};
struct HashFunc
{
std::size_t operator()(const Node &key) const
{
using std::size_t;
using std::hash;
return ((hash<int>()(key.first)
^ (hash<int>()(key.second) << 1)) >> 1)
^ (hash<int>()(key.third) << 1);
}
};
struct EqualKey
{
bool operator () (const Node &lhs, const Node &rhs) const
{
return lhs.first == rhs.first
&& lhs.second == rhs.second
&& lhs.third == rhs.third;
}
};
int main()
{
unordered_map<Node, int, HashFunc,EqualKey> h;
Node key1(1, 2, 3);
h[key1] = 1;
Node key2(3, 4, 45);
cout << h[key1] << endl;
cout << h[key2] << endl;
system("pause");
return 0;
}#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
struct HashFunc
{
std::size_t operator()(const vector<int> &key) const
{
using std::size_t;
using std::hash;
size_t res = hash<int>()(key[0]);
for (int i = 1; i < key.size(); ++i)
{
res ^= (hash<int>()(key[i]) << (i % 2));
}
return res;
}
};
struct EqualKey
{
bool operator () (const vector<int> &lhs, const vector<int> &rhs) const
{
for (int i = 0; i < lhs.size(); ++i)
{
if (lhs[i] != rhs[i])
return false;
}
return true;
}
};
int main()
{
unordered_map<vector<int>, int, HashFunc, EqualKey> h;
vector<int> key1 = { 1, 2, 3 };
vector<int> key2 = { 2, 3, 4 };
h[key1] = 3;
cout << h[key1] << endl;
cout << h[key2] << endl;
system("pause");
return 0;
}
1334

被折叠的 条评论
为什么被折叠?



