//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;
目前想到的就是这两种方法,经过以上的代码检测可以使用,不知道还有没有什么其他更好的方法。
本文探讨了在C++中对map中存储的指针进行修改的两种方案:使用const_cast修改key和通过erase与insert操作value。在Plan1中,通过const_cast去除key的const属性可能引发未定义行为。而在Plan2中,通过先保存指针,erase后再insert,确保了安全。这种方法避免了直接修改const key的风险。
1020

被折叠的 条评论
为什么被折叠?



