我为unordered_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
std
效率的担忧。 - Angew is no longer proud of SO