pair<int,int> pair as key of unordered_map issue
My code:
typedef pair<int,int> Pair
tr1::unordered_map<Pair,bool> h;
h.insert(make_pair(Pair(0,0),true));
Erorr
undefined reference to `std::tr1::hash<std::pair<int, int> >::operator()(std::pair<int, int>) const'
Something I need to fix?
thanks
This happens because there is no specialization for std::tr1::hash<Key>
with Key = std::pair<int, int>
.
You must to specialize std::tr1::hash<Key>
with Key = std::pair<int, int>
before declaring tr1::unordered_map<Pair,bool> h;
.
This happens because std
don't know how to hash a pair<int, int>
.
Following there is a example of how to specialize std::tr1::hash<>
template <>
struct std::tr1::hash<std::pair<int, int> > {
public:
size_t operator()(std::pair<int, int> x) const throw() {
size_t h = SOMETHING;//something with x
return h;
}
};
Unordered Map does not contain a hash function for a pair, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair.
If we want to use pair as a key to unordered_map, there are 2 ways to do it :
- Define specializaion for std::hash
typedef std::pair<std::string,std::string> pair;
struct pair_hash
{
template <class T1, class T2>
std::size_t operator() (const std::pair<T1, T2> &pair) const
{
return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
}
};
int main()
{
std::unordered_map<pair,int,pair_hash> unordered_map =
{
{{"C++", "C++11"}, 2011},
{{"C++", "C++14"}, 2014},
{{"C++", "C++17"}, 2017},
{{"Java", "Java 7"}, 2011},
{{"Java", "Java 8"}, 2014},
{{"Java", "Java 9"}, 2017}
};
for (auto const &entry: unordered_map)
{
auto key_pair = entry.first;
std::cout << "{" << key_pair.first << "," << key_pair.second << "}, "
<< entry.second << '\n';
}
return 0;
}
- Using Boost Library Another good way is to use boost::hash from Boost.functional which can be used to hash integers,floats,pointers,strings,arrays,pairs and theh STL containers.
#include <iostream>
#include <boost/functional/hash.hpp>
#include <unordered_map>
#include <utility>
typedef std::pair<std::string,std::string> pair;
int main()
{
std::unordered_map<pair,int,boost::hash<pair>> unordered_map =
{
{{"C++", "C++11"}, 2011},
{{"C++", "C++14"}, 2014},
{{"C++", "C++17"}, 2017},
{{"Java", "Java 7"}, 2011},
{{"Java", "Java 8"}, 2014},
{{"Java", "Java 9"}, 2017}
};
for (auto const &entry: unordered_map)
{
auto key_pair = entry.first;
std::cout << "{" << key_pair.first << "," << key_pair.second << "}, "
<< entry.second << '\n';
}
return 0;
}