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


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

相关推荐
lihao lihao几秒前
c++红黑树
算法
Sarvartha几秒前
递推与递归笔记
算法
TracyCoder12324 分钟前
LeetCode Hot100(1/100)——1. 两数之和 (Two Sum)
算法·leetcode
进击的小头28 分钟前
常用数字滤波器的特性与适用场景
c语言·算法
APIshop44 分钟前
Java获取item_get-获得某书商品详情接口
java·开发语言·python
狐571 小时前
2026-01-19-LeetCode刷题笔记-1292-元素和小于等于阈值的正方形的最大边长
笔记·算法·leetcode
Henry Zhu1231 小时前
Qt Model/View架构详解(四):高级特性
开发语言·qt·架构
张祥6422889041 小时前
误差理论与测量平差基础笔记六
笔记·算法·概率论
txinyu的博客1 小时前
std::function
服务器·开发语言·c++
多多*2 小时前
图解Redis的分布式锁的历程 从单机到集群
java·开发语言·javascript·vue.js·spring·tomcat·maven