我正在尝试使用unordered_map
将密钥作为一对uint
和类Tile
的值。
#include <iostream>
#include <unordered_map>
#include <boost/functional/hash.hpp>
class Tile {
public:
std::pair<uint, uint> coordinate;
bool operator==(const Tile &t) {
return this->coordinate.first == t.coordinate.first
&& this->coordinate.second == t.coordinate.second;
}
Tile (uint x, uint y) {
this->coordinate.first = x;
this->coordinate.second = y;
}
std::pair<uint, uint> GetCoor() const
{return this->coordinate;}
uint GetX() const
{return coordinate.first;}
uint GetY() const
{return coordinate.second;}
};
struct TileHash {
std::size_t operator()(const Tile &t) const
{
size_t seed = 0;
boost::hash_combine (seed, t.GetX());
boost::hash_combine (seed, t.GetY());
return seed;
}
};
int main ()
{
std::unordered_map<std::pair<uint, uint>, Tile, TileHash> board;
Tile t1 = Tile (0, 0);
board.insert (std::make_pair (t1.GetCoor(), t1));
//board[t1.GetCoor()] = t1; // This causes a different error at compile time...
}
我收到以下错误,然后是我未粘贴的一些注释
/usr/include/c++/v1/unordered_map:400:17: error: no matching function for call to object of type 'const TileHash'
{return static_cast<const _Hash&>(*this)(__x.__cc.first);}
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/v1/__hash_table:1712:21: note: in instantiation of member function 'std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>,
Tile>, TileHash, true>::operator()' requested here
size_t __hash = hash_function()(__x);
^
/usr/include/c++/v1/__hash_table:1692:12: note: in instantiation of member function 'std::__1::__hash_table<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>,
std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, TileHash, true>, std::__1::__unordered_map_equal<std::__1::pair<unsigned
int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, std::__1::equal_to<std::__1::pair<unsigned int, unsigned int> >, true>,
std::__1::allocator<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile> > >::__insert_unique_value' requested here
return __insert_unique_value(__x);
我知道我unordered_map
的实例化是可以的,当我编译时没有调用插入all就好了。
答案 0 :(得分:6)
通过TileHash
,你提供了一个const Tile&
的哈希函数。
该实现正在寻找一个带const std::pair<uint, uint>&
的哈希函数。
那是因为它是被散列的关键,而不是映射值。
所以,你是在做错事。
该标准并没有给我们配对,但Boost确实如此:
std::unordered_map<
std::pair<uint, uint>,
Tile,
boost::hash<std::pair<uint, uint>>
> board;