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


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

相关推荐
阿卡蒂奥33 分钟前
C# 结合PaddleOCRSharp搭建Http网络服务
开发语言·http·c#
kingmax5421200843 分钟前
【洛谷P9303题解】AC- [CCC 2023 J5] CCC Word Hunt
数据结构·c++·算法·广度优先
白熊1881 小时前
【机器学习基础】机器学习入门核心算法:XGBoost 和 LightGBM
人工智能·算法·机器学习
bai_lan_ya2 小时前
数据结构-排序-排序的七种算法(2)
数据结构·算法·排序算法
泉飒2 小时前
lua注意事项
开发语言·笔记·lua
hao_wujing3 小时前
使用逆强化学习对网络攻击者的行为偏好进行建模
开发语言·网络·php
还是鼠鼠3 小时前
单元测试-概述&入门
java·开发语言·后端·单元测试·log4j·maven
全域智图3 小时前
元胞自动机(Cellular Automata, CA)
人工智能·算法·机器学习
珂朵莉MM3 小时前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
独家回忆3643 小时前
每日算法-250601
数据结构·算法