Boost logo

Boost Users :

Subject: Re: [Boost-users] Using unordered_set or unordered_map to hold small array(s) of ints
From: Nathan Crookston (nathan.crookston_at_[hidden])
Date: 2010-08-20 23:10:25


On Fri, Aug 20, 2010 at 5:22 PM, B Hart <bhartsb_at_[hidden]> wrote:
> well assuming an unsigned int array size of 5 what do you suggest for a
> reasonably good and fast hash?
>
> I was hoping that I could use the built in hash w/o having to invent one.
>

boost::hash is actually very nicely extensible. It works with a
number of containers (I was surprised it didn't support boost::array
(or std::array) out of the box), and adding support for something like
boost::array is pretty trivial. See below:

#include <boost/array.hpp>
#include <boost/functional/hash.hpp>
#include <boost/unordered_set.hpp>

typedef boost::array<int, 5> Array;

namespace boost {
template <typename T, std::size_t N>
std::size_t hash_value(const boost::array<T,N>& arr)
{
  return boost::hash_range(arr.begin(), arr.end());
}}

int main(int argc, char* argv[])
{
  Array arr1 = {1000, 3344455, 12455222, 8832232, 1234};
  Array arr2 = {2000, 4344455, 22455222, 16832232, 2345};

  boost::unordered_set<Array> mySet;
  mySet.insert(arr1);

  assert(mySet.find(arr2) == mySet.end() && "Found wrong array");
  assert(mySet.find(arr1) != mySet.end() && "Not finding correct array");

  return 0;
}

HTH,

Nate


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net