【C++学习】两种不改变value只改变map中的key的方式

本文探讨了在C++中对map中存储的指针进行修改的两种方案:使用const_cast修改key和通过erase与insert操作value。在Plan1中,通过const_cast去除key的const属性可能引发未定义行为。而在Plan2中,通过先保存指针,erase后再insert,确保了安全。这种方法避免了直接修改const key的风险。
	//Plan1: 使用const_cast将map的key去掉const,可能会引发问题

	int a = 10;
	int* b = &a;
	std::map<int, int*> testList;
	testList.insert(std::pair<int, int*>(1, std::move(b)));
	auto it = testList.find(1);
	int* temp = const_cast<int*>(&it->first);
	*temp = 4;
	auto it1 = testList.find(4);
	cout << *it1->second << endl;

	//Plan2: 当value为指针时,erase不会析构value对象,可以对其进行erase
	//			但是需要注意使用一个temp来存放指针,然后再erase,insert.

	int a = 10;
	int* b = &a;
	std::map<int, int*> testList;
	testList.insert(std::pair<int, int*>(1, std::move(b)));
	auto it = testList.find(1);
	cout << b << endl;
	auto temp = it->second;
	testList.erase(1);
	testList.insert(std::pair<int, int*>(2, temp));
	cout << testList.size() << endl;
	cout << testList.find(2)->second << endl;

目前想到的就是这两种方法,经过以上的代码检测可以使用,不知道还有没有什么其他更好的方法。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值