How to use std :: unordered_set in c ++?

I chose the concept of hash tables in Java, so I knew that for a universal hash set container for custom classes, you had to provide a definition of the hash function and the corresponding equality function.

In Java, this would mean an overriding method.

int hashCode() 

and

 boolean equals (Object o) 

.

I expected the same logic in the C ++ STL, but had difficulty understanding the syntax. In particular, std :: unordered_set <> takes 5 arguments to the template (can you believe it?), Which looks like a monster and makes my head spin.

So, I would appreciate it if you could give a simple example for the current class of toys:

 class Some{ public : int a; }; 

The a value is simply returned from the hash function, and the equality checking functions return true if the values โ€‹โ€‹of the 'a' member are the same.

thanks

+1
source share
2 answers

Step 1: Overloading operator== for your type:

 bool operator==(const Some& x, const Some& y) { return xa == ya; } 

Step 2: Specialize std::hash for your type:

 namespace std { template<> struct hash<Some> { typedef Some argument_type; typedef size_t result_type; size_t operator()(const Some& x) const { return xa; } }; } 

Step 3: A simple test:

 int main() { std::unordered_set<Some> test; test.insert(Some{42}); } 

Step 4: Profit!

+4
source

I don't have a compiler, so there may be errors, but it should be something similar to:

 namespace std { template <> struct hash<Some> { typedef Some argument_type; typedef std::size_t result_type; result_type operator()(const Some & t) const { return ta; } }; } 
+1
source

Source: https://habr.com/ru/post/911945/


All Articles