我已经为 unrorderd_map 定义了我自己的哈希函数。但我无法使用 find 功能在容器中搜索。我尝试在散列函数中使用打印语句进行调试,它生成的散列值与插入键/值时生成的散列值相同。如果有人能指出错误,那就太好了。我在 Windows 上使用 Eclipse IDE,并且正在使用 -std=c++11 进行编译
typedef struct tree node;
struct tree
{
int id;
node *left;
node *right;
};
class OwnHash
{
public:
std::size_t operator() (const node *c) const
{
cout << "Inside_OwnHash: " <<std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right) << endl;
return std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right);
}
};
int main()
{
std::unordered_map<node *,node *,OwnHash> ut;
node * one = new node;
one->id = -1;
one->left = nullptr;
one->right = nullptr;
ut.insert({one,one});
node * zero = new node;
zero->id = 0;
zero->left = NULL;
zero->right = NULL;
ut.insert({zero,zero});
node * cur = new node;
cur->id = 5;
cur->left = zero;
cur->right = one;
ut.insert({cur,cur});
for (auto& elem : ut)
{
std::cout << "key: " << elem.first << "\t" << "value: " << elem.second->id << std::endl;
}
node * parse = new node;
parse->id = 5;
parse->left = zero;
parse->right = one;
std::unordered_map<node *,node *>::const_iterator got1 = ut.find (parse);
if ( got1 == ut.end() )
std::cout << "not found";
else
std::cout << got1->first << " is " << got1->second->id << std::endl;
return EXIT_SUCCESS;
}
Output:
Inside_OwnHash: 4294967295
Inside_OwnHash: 0
Inside_OwnHash: 22946517
key: 0xaf11b0 value: 5
key: 0xaf1180 value: 0
key: 0xaf1150 value: -1
Inside_OwnHash: 22946517
not found