c++ - User defined hash function for unordered map -


i have defined own hash function unrorderd_map. unable search in container using find function. have tried debugging using print statement within hash function , generates same hash value generated while inserting key/value. great if point out error. using eclipse ide on windows , compiling -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 * 1 = new node; one->id = -1; one->left = nullptr; one->right = nullptr; ut.insert({one,one});  node * 0 = 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});  (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 << " " << 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 

hash not enough, must implement equality comparison too!

the hash has function such if items equal, hash equal. since items may arbitrarily complex , hash result size_t, opposite implication not , cannot hold. find exact element, need equality comparison too.

when looking up, hash function points right "bucket", there may multiple elements in or there may element there, not 1 looking for. takes elements in bucket , compares each 1 searching.

now provided hash function, did not provide equality comparator. uses default, operator== , pointers defined comparing addresses. , addresses not equal. need provide equality functor compares values.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -