[Aprendizaje C++] Dos formas de cambiar la clave en el mapa sin cambiar el valor

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

Estos dos métodos son lo que pienso en este momento, y se pueden usar después de la detección del código anterior. No sé si hay otros métodos mejores.

Supongo que te gusta

Origin blog.csdn.net/Daibvly/article/details/123878956
Recomendado
Clasificación