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


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

相关推荐
Tryagein2 分钟前
【数据结构】并查集
数据结构·算法
Joe_Wang56 分钟前
[数据结构]并查集(系统整理版)
数据结构·c++·算法·leetcode·并查集
啊阿狸不会拉杆1 小时前
第十五章:Python的Pandas库详解及常见用法
开发语言·python·数据分析·pandas
进击的jerk2 小时前
力扣.旋转矩阵Ⅱ
算法·leetcode·矩阵
Jcqsunny3 小时前
[分层图] 汽车加油行驶问题
算法·dp·分层图·分层图dp
rqtz3 小时前
【C++指针】搭建起程序与内存深度交互的桥梁(下)
开发语言·c++·指针
熬夜造bug3 小时前
LeetCode Hot100 刷题笔记(4)—— 二叉树、图论
笔记·算法·leetcode
小陈的进阶之路3 小时前
数据结构(并查集,图)
数据结构·c++·算法
AI让世界更懂你3 小时前
Python 包管理器 UV 全面介绍
开发语言·python·uv
IT猿手3 小时前
基于烟花算法(Fireworks Algorithm,FWA)及三次样条的机器人路径规划,50个场景任意选择,完整MATLAB代码
开发语言·算法·机器学习·matlab·机器人·无人机