Search code examples
c++std-pairunordered-set

How can I make an unordered set of pairs of integers in C++?


The following program does not compile an unordered set of pairs of integers, but it does for integers. Can unordered_set and its member functions be used on user-defined types, and how can I define it?

#include <unordered_set>
...

class A{
...
private: 
    std::unordered_set< std::pair<int, int> > u_edge_;
};

Compiler error:

error: no matching function for call to 'std::unordered_set >::unordered_set()'


Solution

  • Your code compiles on VS2010 SP1 (VC10), but it fails to compile with GCC g++ 4.7.2.

    However, you may want to consider boost::hash from Boost.Functional to hash a std::pair (with this addition, your code compiles also with g++).

    #include <unordered_set>
    #include <boost/functional/hash.hpp>
    
    class A
    {
    private: 
        std::unordered_set< 
            std::pair<int, int>, 
            boost::hash< std::pair<int, int> > 
        > u_edge_;
    };