【发布时间】:2015-09-16 15:50:18
【问题描述】:
我想在 unordered_set 中找到一个值,但是失败了:
typedef std::shared_ptr<int> IntPtr;
std::unordered_set<IntPtr> s;
s.insert(std::make_shared<int>(42));
bool found = s.find(std::make_shared<int>(42)) != s.end();
cout<<std::boolalpha<<found<<endl; // false
已尝试关注但仍然无法正常工作。
namespace std {
template <> struct hash<IntPtr> {
size_t operator()(const IntPtr& x) const noexcept {
return std::hash<int>()(*x);
}
};
}
知道如何让它工作吗?
【问题讨论】:
-
您需要了解两个共享指针“相等”的含义。
-
你不应该专门化
std::hash而不是你的类型... -
shared_ptr的比较运算符比较指针值;不比较指向的实际对象。
标签: c++ shared-ptr unordered-set