简体   繁体   中英

Why does std::set<array<int,N>> work but not std::unordered_set<array<int,N>>?

Same goes for std::unordered_map vs std::map . It means that std::map can store objects of type std::array<T,N> for primitive T's but std::unordered_map cannot.

std::array<T, N> is not hashable by default. So, you need to implement your own hashing function for this type. A simple example hash function can be like this (adopted from here ):

#include <set>
#include <array>
#include <unordered_set>

const int N = 10;


struct array_hasher
{
   std::size_t operator()(std::array<int, N> const& arr) const 
   {
      std::size_t seed = 0;
      for (const auto& i : arr) 
      {
         seed ^= std::hash<int>{}(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
      }
      return seed;
   }
};

int main()
{
   std::set<std::array<int, N>> x = {};
   std::unordered_set<std::array<int, N>, array_hasher> y = {};

   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM