我試圖在映射中保存多態類型作爲鍵。std ::散列在無序映射中的唯一ptr
我想出了以下兩種結構:
注意Game
是一個抽象類,我用的數據結構是:
std::unordered_map<gamePtr,int> _allGames;
而gamePtr
是typedef
爲:
unique_ptr<Game>
template<>
struct std::hash<std::unique_ptr<Game>> {
size_t operator()(std::unique_ptr<Game> game) const {
return (std::hash<string>()(std::to_string(game->firstTeamFinalScore()) + game->firstTeam() + game->secondTeam()));
}
};
struct cmp_games {
bool operator() (std::unique_ptr<Game> game1, std::unique_ptr<Game> game2) const {
return *game1 == *game2;
}
};
cmp_games
比較器似乎工作正常,但std::hash
不因爲它試圖複製一個unique_ptr
(這是不可能的),我不知道如何克服它。 很想聽聽一些建議(如果甚至可能的話)。
編輯:比較器也似乎不能正常工作。我如何使這張地圖能夠正確地與unique_ptr
一起工作?
EDIT2:
趕上了:
template<>
struct std::hash<std::unique_ptr<Game>> {
size_t operator()(const std::unique_ptr<Game>& game) const {
return (std::hash<string>()(std::to_string(game->firstTeamFinalScore()) + game->firstTeam() + game->secondTeam()));
}
};
template<>
struct std::equal_to<std::unique_ptr<Game>> {
bool operator() (const std::unique_ptr<Game>& game1,const std::unique_ptr<Game>& game2) const {
return *game1 == *game2;
}
};
他們應該夠嗎?
通過引用'operator()'傳遞'unique_ptr'? – Nabla
不管標準是否爲std :: unique_ptr定義了std :: hash?它在cppreference上:http://en.cppreference。com/w/cpp/memory/unique_ptr/hash – jogojapan
@jogojapan在我看來,標準哈希由指針地址散列,而提問者想要散列指針指向的對象值,請參閱他們的'cmp_games'實現。 – Nabla