【C++学习】两种不改变value只改变map中的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;

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值