C ++ How to insert an array in unordered_map as a key?

Hi, I used unordered_set to store my 16 int array, now I need to save another int as my bucket. I wonder if I can insert an array into my unordered_set or use the same template that I used?

#include <unordered_set> #include <array> namespace std { template<typename T, size_t N> struct hash<array<T, N> > { typedef array<T, N> argument_type; typedef size_t result_type; result_type operator()(const argument_type& a) const { hash<T> hasher; result_type h = 0; for (result_type i = 0; i < N; ++i) { h = h * 31 + hasher(a[i]); } return h; } }; } std::unordered_set<std::array<int, 16> > closelist; int main() { std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}; closelist.insert(sn); } 

Can I just change it to this?

 std::unordered_map<std::array<int, 16>,int > closelist; int main() { std::array<int, 16> sn = {1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}; closelist.insert(sn,24); } 

And I could not understand the template, I wonder what is "h = h * 31 + hasher (a [i]);"?

Thanks!!!

+6
source share
2 answers

Can I just change it to this?

Firstly, the initialization of your array is incorrect:

 std::array<int, 16> sn = {{1,2,3,4,5,6,0,8,9,10,11,12,13,14,7,15}}; // ^ ^ 

Since std::array does not have a constructor with std::initializer_list as an argument. So, the first level is to initialize the object, the second is to initialize the array in the object.

Secondly, from reference :

 std::pair<iterator,bool> insert( const value_type& value ); template <class P> std::pair<iterator,bool> insert( P&& value ); 

So you have to pass std::pair (or something convertible to std::pair ), for example:

 closelist.insert({sn,24}); 

Or easier:

 closelist[sn] = 24; 
+1
source

How to use any object as a key:

  • Serialize the object into an array of bytes (for an int array, just use the binary data as it is)
  • Calculate cryptographic hash (MD5 or SHA)
  • Convert a cryptographic hash to a fingerprint value (for example, translate its first 64 bits to uint64_t)
  • Use this fingerprint as a card key.

The downside is that you may need to resolve conflicts.

+1
source

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


All Articles