class A;
有序map:
std::unordered_map<std::weak_ptr<A>, int, A, std::owner_less<A>> text;
无序map:
class A
{
public:
A() : a(0) {}
A(int ss) : a(ss) {}
std::size_t hash() const { return std::hash<int>()(a); }
std::size_t operator()(const std::weak_ptr<A> &p) const
{
if (p.expired())
return 0;
auto sharedPtr = p.lock();
if (!sharedPtr)
return 0;
return sharedPtr->hash();
}
bool operator==(const std::weak_ptr<A> &other) const
{
std::shared_ptr<A> otherPtr;
if (other.expired())
otherPtr = nullptr;
else
otherPtr = other.lock();
if (!otherPtr)
return false;
return hash() == otherPtr->hash();
}
class CharCmp
{
public:
bool operator()(const std::weak_ptr<A> &p, const std::weak_ptr<A> &other) const
{
std::shared_ptr<A> selfPtr;
std::shared_ptr<A> otherPtr;
if (p.expired())
selfPtr = nullptr;
else
selfPtr = p.lock();
if (other.expired())
otherPtr = nullptr;
else
otherPtr = other.lock();
if (selfPtr == otherPtr)
return true;
if (!selfPtr)
return false;
if (!otherPtr)
return false;
return selfPtr->hash() == otherPtr->hash();
}
};
int a = 0;
};
auto ptr = std::make_shared<A>(2);
std::unordered_map<std::weak_ptr<A>, int, A, A::CharCmp> text;
text.emplace(ptr, 0);
ptr->a = 3;
text.emplace(ptr, 0);
ptr = std::make_shared<A>(2);
text.emplace(ptr, 0);