如何正确删除指针映射作为键?(How to properly delete a map of pointers as key?)

编程入门 行业动态 更新时间:2024-10-24 17:34:05
如何正确删除指针映射作为键?(How to properly delete a map of pointers as key?)

我有一个键/值指针的映射:

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

更多推荐

本文发布于:2023-08-06 17:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   如何正确   properly   delete   pointers

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!