unorder_map 自定义KEY

时间:2023-03-09 08:59:18
unorder_map 自定义KEY

1. boost::unorder_map 实现自定义KEY

 // boostLibTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h" #include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>
#include <set>
#include <map>
#include <unordered_map> using namespace std; struct Test
{
int _id;
string _name;
set<int> _nums; Test(int id, string name, set<int> nums = set<int>()) :
_id(id), _name(name), _nums(nums)
{
}
}; bool operator==(const Test& ts1, const Test& ts2)
{
return ts1._id == ts2._id && ts1._name == ts2._name && ts1._nums == ts2._nums;
} size_t hash_value(const Test& test)
{
std::size_t seed = ;
boost::hash_combine(seed, std::hash_value(test._id));
boost::hash_combine(seed, std::hash_value(test._name));
for (auto& iter : test._nums){
boost::hash_combine(seed, std::hash_value(iter));
}
return seed;
} int _tmain(int argc, _TCHAR* argv[])
{
set<int> sets = {,,,,};
boost::unordered_map<Test, string> map;
map.insert(make_pair(Test(, "abc", sets), ""));
map.insert(make_pair(Test(, "def", sets), ""));
map.insert(make_pair(Test(, "egh", sets), ""));
map.insert(make_pair(Test(, "ijk", sets), ""));
map.insert(make_pair(Test(, "lmn", sets), "")); auto iter = map.find(Test(, "egh", sets));
if (iter != map.end()){
cout << "Find !" << endl;
}
else{
cout << "Not Find !" << endl;
} getchar();
return ;
}

输出结果为: Find !

===============================================================

2. std::unorder_map 实现自定义KEY

 // boostLibTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h" #include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <iostream>
#include <set>
#include <map>
#include <unordered_map> using namespace std; struct Test
{
int _id;
string _name;
set<int> _nums; Test(int id, string name, set<int> nums = set<int>()) :
_id(id), _name(name), _nums(nums)
{
}
}; namespace std
{
template<>
struct hash<Test>
: public _Bitwise_hash < Test >
{ // hash functor for RECT
}; inline bool operator == (const Test &ts1, const Test &ts2) _NOEXCEPT
{
return ts1._id == ts2._id && ts1._name == ts2._name && ts1._nums == ts2._nums;
}
} int _tmain(int argc, _TCHAR* argv[])
{
set<int> sets = {,,,,};
std::unordered_map<Test, string> map;
map.insert(make_pair(Test(, "abc", sets), ""));
map.insert(make_pair(Test(, "def", sets), ""));
map.insert(make_pair(Test(, "egh", sets), ""));
map.insert(make_pair(Test(, "ijk", sets), ""));
map.insert(make_pair(Test(, "lmn", sets), "")); auto iter = map.find(Test(, "egh", sets));
if (iter != map.end()){
cout << "Find !" << endl;
}
else{
cout << "Not Find !" << endl;
} getchar();
return ;
}

奇怪的地方来了,std的结果有时候是 Find ! 有时候是 Not Find !

没弄明白这个std::unorder_map怎么回事,我自己直接用了boost::unorder_map