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

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

猜你喜欢

转载自blog.csdn.net/Daibvly/article/details/123878956