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!

6
  • What compiler? Both gcc and clang accept your first definition. Commented Feb 5, 2015 at 22:55
  • I am trying to write a program using MPI so I was using the mpicxx compiler @Praetorian Commented Feb 5, 2015 at 22:58
  • See if it'll compile the code I linked to, if not it might be problem with that compiler. Commented Feb 5, 2015 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. Commented Feb 5, 2015 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. Commented Feb 5, 2015 at 23:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.