我有一个键/值指针的映射:
std::map<A*, B*> myMap;什么是解放密钥记忆的正确方法?
我在想这样做:
for (auto itr = _myMap.begin(); itr != _myMap.end(); itr++) { if (certainCondition == true) { delete itr->first; itr->first = nullptr; } }这是正确的做法吗? 我的地图会将nullptr保留为关键,未来的迭代会包含nullptr吗?
I have a map of key/value pointers :
std::map<A*, B*> myMap;What would be the proper way to liberate the memory of the key only?
I was thinking about doing this :
for (auto itr = _myMap.begin(); itr != _myMap.end(); itr++) { if (certainCondition == true) { delete itr->first; itr->first = nullptr; } }Is it the correct way of doing it? Will my map keep nullptr as a key and future iteration will include nullptr?
最满意答案
您无法修改容器的键,因为它用于定义排序,并且在适当的位置更改它可能使排序无效。 此外,每个密钥都必须是唯一的。 因此,您需要从地图中删除该项目然后清理内存。
如果您已经拥有密钥:
myMap.erase(key); delete key;如果你已经在地图中有一个迭代器:
A* keyCopy = itr->first; myMap.erase(itr); delete keyCopy;编辑
根据您更新的问题:
auto itr = myMap.begin(); while (itr != myMap.end()) { if (certainCondition == true) { A* keyCopy = itr->first; itr = myMap.erase(itr); delete keyCopy; } else { ++itr; } }You cannot modify the key of the container because it is used to define the ordering and changing it in place could invalidate the ordering. Furthermore, each key needs to be unique. Therefore, you need to remove the item from the map then clean up the memory.
If you already have the key:
myMap.erase(key); delete key;If you already have an iterator within the map:
A* keyCopy = itr->first; myMap.erase(itr); delete keyCopy;Edit
Per your updated question:
auto itr = myMap.begin(); while (itr != myMap.end()) { if (certainCondition == true) { A* keyCopy = itr->first; itr = myMap.erase(itr); delete keyCopy; } else { ++itr; } }更多推荐
发布评论