C++ unordered_map with custom hash issues -


i trying write custom hash function use in unordered_map. able insert items , iterate through them, cannot lookup items using at(), find() or operator[] functions.

#include <cstddef> #include <iostream> #include <functional> #include <random> #include <unordered_map>  #include <stdint.h> #include <stdio.h> #include <stdlib.h>  #define jhash_golden_ratio  0x9e3779b9  using namespace std;  #define __jhash_mix(a, b, c) \ { \   -= b; -= c; ^= (c>>13); \   b -= c; b -= a; b ^= (a<<8); \   c -= a; c -= b; c ^= (b>>13); \   -= b; -= c; ^= (c>>12);  \   b -= c; b -= a; b ^= (a<<16); \   c -= a; c -= b; c ^= (b>>5); \   -= b; -= c; ^= (c>>3);  \   b -= c; b -= a; b ^= (a<<10); \   c -= a; c -= b; c ^= (b>>15); \ }  uint32_t jhash_3words (uint32_t a, uint32_t b, uint32_t c, uint32_t initval) {   += jhash_golden_ratio;   b += jhash_golden_ratio;   c += initval;    __jhash_mix (a, b, c);    return c; }  size_t jenkins_hash(const uint32_t &num){     return (size_t) jhash_3words (num, 0, 0, rand()); }  int main(){      std::unordered_map<uint32_t, char, std::function<decltype(jenkins_hash)>> ids(0, jenkins_hash );          ids[(uint32_t) 42341] = 'g';         ids[(uint32_t) 2232] = 'b';         ids[(uint32_t) 7556] = 'q';      ( auto = ids.begin(); != ids.end(); ++it ){         std::cout << "element " << it->first << " " << it->second << std::endl;     }     std::cout << ids.size() << std::endl;      printf("%c\n", ids.find(7556)->second);       return 0; } 

here output of above code:

element 2232 b element 7556 q element 42341 g 3 segmentation fault (core dumped) 

my questions are...

  • why producing segfault?

  • why at() , operator[] return nothing, whereas find() segfaults?

any ideas?

size_t jenkins_hash(const uint32_t &num){     return (size_t) jhash_3words (num, 0, 0, rand()); } 

since hash function includes random element, 2 times 7556 hashed yield different hashed values. means lookup done find fails locate , returns ids.end(), should not dereference.

here's how should using find():

auto found = ids.find(7556); if(found != ids.end()) {   printf("%c\n", found->second); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -