0

I wanted to create a custom hash function for an unordered map. I found this question: C++ unordered_map fail when used with a vector as key and found that if you use a vector as a key in an unordered map, you need to create your own hash function. I experimented copying the hash function written as so:

template <typename Container> 
struct container_hash {
    std::size_t operator()(Container const& c) const {
        return boost::hash_range(c.begin(), c.end());
    }
};

But when I try to create an unordered_map with my keys as a vector of ints like so:,

unordered_map<vector<int>, int, container_hash<vector<int>>> hash;

I get an issue saying that:

error: declaration of ‘struct std::hash<std::vector<int> >’

I have tried other ways to include the container_hash function into the implementation of my unordered_map by trying things like

unordered_map<vector<int>, int, container_hash> hash;

But again I get another error saying:

type/value mismatch at argument 3 in template parameter list for ‘template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map’

I'm really not sure how to get around this, if anyone could help me that would be great! Thanks!

Community
  • 1
  • 1
user1871869
  • 3,317
  • 13
  • 56
  • 106
  • What compiler? Both gcc and clang [accept](http://coliru.stacked-crooked.com/a/e4988e4aad76243f) your first definition. – Praetorian Feb 05 '15 at 22:55
  • I am trying to write a program using MPI so I was using the mpicxx compiler @Praetorian – user1871869 Feb 05 '15 at 22:58
  • See if it'll compile the code I linked to, if not it might be problem with that compiler. – Praetorian Feb 05 '15 at 23:00
  • @Praetorian interestingly enough it does compile. I don't think I have anything different from what you had written in the code you linked either. – user1871869 Feb 05 '15 at 23:03
  • @Praetorian Ah nevermind. I found the issue. It was somewhere else in my code. I apologize and thank you so much for helping me out with this. – user1871869 Feb 05 '15 at 23:06
  • Probably the insufficient spacing for ">>" in template closing brackets? – fche Aug 07 '15 at 14:02

1 Answers1

1

This code compiles just fine:

#include <vector>
#include <boost/unordered_map.hpp>

template <typename Container>
struct container_hash {
    std::size_t operator()(Container const& c) const {
    return boost::hash_range(c.begin(), c.end());
    }
};

int main()
{
    boost::unordered_map
        <std::vector <int>, int,
         container_hash <std::vector  <int> > > foo;
    return 0;
}

Your problem is likely elsewhere.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278