Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pair as key for hash_map under Visual Studio

Try to use pair as key value for hash_map under Visual Studio 2010.

Could not compile it.

int _tmain(int argc, _TCHAR* argv[]) 
{
   hash_map <pair<int, int>, int> months;
    months[pair<int, int>(2,3)] = 1;

   int d;
   cin >> d;

   return 0;
}

got error message:

Error 1 error C2440: 'type cast' : cannot convert from 'const std::pair<_Ty1,_Ty2>' to 'size_t' c:\program files\microsoft visual studio 10.0\vc\include\xhash 34 1 testApplication1

I know it probably due to hash_map doesn't provide a specialization for pair. Any easy way to fix it?

like image 876
user2030574 Avatar asked Feb 14 '13 15:02

user2030574


People also ask

Can I have pair as key for unordered_ map?

Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair.

Can map keys be paired?

So, you can use pair as a key in a map as follows: map<pair<int,string> , long> mp; mp.

Is C++ pair hashable?

However, std::pair is not hashable by default, so a simple snippet like the above would not work. There are many proposals online to define a pairhash class and explicitly specify it as the hash function as a template parameter to std::unordered_set and std::unordered_map . This is not a bad idea.


2 Answers

You have to write your own hash_compare - function for the object you're using as key!

In your case is it std::pair<int,int>

look at this post - maybe you get a better idea implementing your own comparator!

like image 196
jenseb Avatar answered Oct 27 '22 19:10

jenseb


Here's a very simple example of a pair<int,int> hash functor, it should give you enough of a start to implement your own:

using namespace std;

class pair_hasher
{
public:
    size_t operator()(const pair<int, int> & p) const
    {
        return p.first*100 + p.second*10000;
    }
};

typedef unordered_map <pair<int, int>, int, pair_hasher> pair_map;

int _tmain(int argc, _TCHAR* argv[])
{
    pair_map months;
    pair<int, int> p = make_pair<int, int>(2,3);
    months[p] = 1;
    cout << months[p] << endl;

    return 0;
}
like image 35
Benj Avatar answered Oct 27 '22 19:10

Benj