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


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

相关推荐
Charles Ray31 分钟前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码32 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文34 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
limingade3 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信
编程零零七3 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286114 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py4 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy4 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
jiao000015 小时前
数据结构——队列
c语言·数据结构·算法
C-SDN花园GGbond5 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法