C++弱指针做map键值

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


创作不易,小小的支持一下吧!

相关推荐
sweet丶14 分钟前
适合iOS开发的一种缓存策略YYCache库 的原理
算法·架构
是宇写的啊27 分钟前
算法—滑动窗口
算法
沐知全栈开发28 分钟前
ionic 选项卡栏操作详解
开发语言
曹牧37 分钟前
C#中,#region和#endregion
开发语言·c#
顾安r38 分钟前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
风筝在晴天搁浅40 分钟前
代码随想录 509.斐波那契数
数据结构·算法
落落落sss1 小时前
java实现排序
java·数据结构·算法
蒙小萌19931 小时前
Swift UIKit MVVM + RxSwift Development Rules
开发语言·prompt·swift·rxswift
Z***25801 小时前
Java爬虫框架
java·开发语言·爬虫
limenga1021 小时前
支持向量机(SVM)深度解析:理解最大间隔原理
算法·机器学习·支持向量机