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


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

相关推荐
weixin_446122462 分钟前
LinkedList剖析
算法
GiraKoo5 分钟前
【GiraKoo】C++14的新特性
c++
软件黑马王子10 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon11 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉15 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
Da_秀19 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte26 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
坏柠30 分钟前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
泽02021 小时前
C++之红黑树认识与实现
java·c++·rpc
百年孤独_1 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表