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作为键使此地图正常工作?

编辑2:

想出了:

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;
}
};

它们应该足够吗?

该标准提供了一个规范,以便std::hash<unique_ptr<T>>std::hash<T*>相同。因此,为std::hash<Game *>提供专业化.例如:

#include <iostream>
#include <memory>
#include <unordered_map>
#include <cstdlib>
struct foo 
{
    foo(unsigned i) : i(i) {}
    unsigned i;
};
namespace std {
template<>
struct hash<foo *>
{
    size_t operator()(foo const *f) const
    {
        std::cout << "Hashing foo: " << f->i << 'n';
        return f->i;;
    }
};
}
int main()
{
    std::unordered_map<std::unique_ptr<foo>, int> m;
    m.insert(std::make_pair(std::unique_ptr<foo>(new foo(10)), 100));
    m.insert(std::make_pair(std::unique_ptr<foo>(new foo(20)), 200));
}

现场演示


另一种选择是更改现有的std::hash专业化,以便通过引用获取unique_ptr

size_t operator()(std::unique_ptr<Game> const& game) const
//                                      ^^^^^^ no more copying

编辑:std::unique_ptr提供了比较托管指针的比较运算符。如果希望unordered_map测试Game对象本身的相等性,请提供operator==重载,而不是专用std::equal_to

inline bool operator==(const std::unique_ptr<Game>& game1, 
                       const std::unique_ptr<Game>& game2) 
{
    return *game1 == *game2;
}

反过来,这需要您为Game提供一个相等运算符(或者您可以将逻辑添加到上面的函数中)。

inline bool operator==(Game const& game1, Game const& game2)
{
    return // however you want to compare these
}

通过常量引用将game传递到std::hash::operator()

template<>
struct std::hash<std::unique_ptr<Game>> {
    size_t operator()(const std::unique_ptr<Game>& game) const;
}

这同样适用于cmp_games::operator()

最新更新