我的代码:
typedef pair<int,int> Pair
tr1::unordered_map<Pair,bool> h;
h.insert(make_pair(Pair(0,0),true));
错误
undefined reference to `std::tr1::hash<std::pair<int, int> >::operator()(std::pair<int, int>) const'
我需要修复什么?
谢谢
我的代码:
typedef pair<int,int> Pair
tr1::unordered_map<Pair,bool> h;
h.insert(make_pair(Pair(0,0),true));
错误
undefined reference to `std::tr1::hash<std::pair<int, int> >::operator()(std::pair<int, int>) const'
我需要修复什么?
谢谢
std::tr1::hash<Key>
发生这种情况是因为with没有专门化Key = std::pair<int, int>
。您必须在声明之前专门std::tr1::hash<Key>
处理. 发生这种情况是因为不知道如何散列一个.Key = std::pair<int, int>
tr1::unordered_map<Pair,bool> h;
std
pair<int, int>
下面是一个如何专门化的例子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 不包含一个对的散列函数,所以如果我们想对一个对进行散列,那么我们必须显式地为它提供一个可以散列一个对的散列函数。
如果我们想使用 pair 作为 unordered_map 的键,有两种方法可以做到:
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;
}
#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;
}
遇到同样的问题:
unordered_map <pair<x, y>, z> m1;
一些解决方法是:
unordered_map <stringxy, z> m1;
// the first and second of the pair merged to a string
// though string parsing may be required, looks same complexity overall
unordered_multimap <x, pair<y, z>> m1;
// second of the pair of the key went into value.
// time complexity slightly increases
deque<deque<x>> d1;
// here x & y are of same type, z is stored as: d1[x][y] = z
// space required is x * y, however time complexity is O(1)