c++ - When should we provide our own Hash function for `std::unordered_set` -


when compile following code, saw errors related hash.

int f_no_meaninga(unordered_set<vector<int>>& setvec, vector<int>& vec)  {     setvec.insert(vec);     return 1; }  int main() {   vector<int> w{2, 3, 7};    unordered_set<vector<int>> setvec;  }  $ g++ --version g++ (ubuntu/linaro 4.6.3-1ubuntu5) 4.6.3  $ g++ $1.cpp -o $1 -g -wall -weffc++ -pedantic -std=c++0x 

/tmp/cccqfq4n.o: in function `std::__detail::_hash_code_base

, std::vector >, std::_identity > >, std::equal_to > >, std::hash > >, std::__detail::_mod_range_hashing, std::__detail::_default_ranged_hash, false>::_m_hash_code(std::vector > const&) const': /usr/include/c++/4.6/bits/hashtable_policy.h:753: undefined reference std::hash<std::vector<int, std::allocator<int> > ::operator()(std::vector<int, std::allocator<int> >) const' /tmp/cccqfq4n.o: in function std::__detail::_hash_code_base , std::vector >, std::_identity > >, std::equal_to > >, std::hash > >, std::__detail::_mod_range_hashing, std::__detail::_default_ranged_hash, false>::_m_bucket_index(std::__detail::_hash_node >, false> const*, unsigned int) const': /usr/include/c++/4.6/bits/hashtable_policy.h:763: undefined reference `std::hash > ::operator()(std::vector >) const' collect2: ld returned 1 exit status

then, introduce following own hash , problem solved.

question 1> when should provide our own hash std::unordered_set? when should provide our own equivalent function std::unordered_set?

struct hashvector : unary_function<vector<int>, vector<int>::size_type> {   vector<int>::size_type operator()(const vector<int>& vec) const {     vector<int>::size_type sum = 0;     for(int : vec) {       sum = sum*37 + hash<int>()(i);     }     return sum;   } };  int f_no_meaningb(unordered_set<vector<int>, hashvector>& setvec, vector<int>& vec)  {     setvec.insert(vec);     return 1; }  int main() {   vector<int> w{2, 3, 7};    unordered_set<vector<int>, hashvector> setvec;  } 

warning: base class ‘struct std::unary_function, unsigned int>’ has non-virtual destructor [-weffc++]

question 2> why g++ complain struct hashvector above warning?

thank you

when should provide our own hash std::unordered_set?

when you're using type doesn't have hash provided standard library. example, doesn't provide hash functions standard containers, including vector<int>.

why g++ complain struct hashvector above warning?

because you've used -weffc++ request (slightly over-zealous) warning tell whenever inherit class no virtual destructor. uses of inheritance (i.e. polymorphism), don't want that. however, in case, inheritance used (or, might say, abused) inject definitions class, warning not indicate problem.

classes std::unary_function deprecated, best solution not inherit @ all.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -