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


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

相关推荐
不見星空几秒前
2025年第十六届蓝桥杯软件赛省赛C/C++大学A组个人解题
c语言·c++·蓝桥杯
@十八子德月生1 分钟前
8天Python从入门到精通【itheima】-1~5
大数据·开发语言·python·学习
jiunian_cn2 分钟前
【c++】异常详解
java·开发语言·数据结构·c++·算法·visual studio
梁下轻语的秋缘10 分钟前
每日c/c++题 备战蓝桥杯(洛谷P1387 最大正方形)
c语言·c++·蓝桥杯
熬夜学编程的小王13 分钟前
【C++进阶篇】多态
c++·多态·静态绑定与动态绑定
martian66513 分钟前
信创生态核心技术栈:数据库与中间件
开发语言·中间件·系统架构·系统安全·创业创新
Bl_a_ck38 分钟前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
UpUpUp……1 小时前
Linux--JsonCpp
linux·运维·服务器·c++·笔记·json
每天一个秃顶小技巧1 小时前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
工藤新一¹1 小时前
蓝桥杯算法题 -蛇形矩阵(方向向量)
c++·算法·矩阵·蓝桥杯·方向向量