我有一个 std::list 和一个 std::map,我想清空它们并在所有指针上调用 delete。
看完this问题我将其用于 std::list:
mylist.remove_if([](myThingy* thingy) -> bool { delete thingy; return true; });
std::map 是否有类似的简洁内容?
请注意,我不能使用基于范围的 for 循环,因为我的编译器 (VC10) 不支持它。如果可能的话,我假设
for(auto* thingy : myMap) { delete thingy; }
myMap.clear();
会起作用。如果我错了,请纠正我。
最佳答案
Is there something similarly concise for std::map?
你可以这样做(假设你的 thingy
是映射值,而不是键):
for_each(myMap.begin(), myMap.end(),
[] (decltype(myMap)::value_type const& p) { delete p.second; });
myMap.clear();
关于基于范围的 for
循环:
If it would be possible I assume
for(auto* thingy : myMap) { delete thingy; } myMap.clear();
would work. Please correct me if I am wrong.
或多或少。您仍然需要记住 map 的值实际上是对 - 但您可以修复基于范围的 for
以考虑到这一点,是的:
for (auto&& p : myMap) { delete p.second; }
myMap.clear();
无论如何,请考虑使用智能指针,而不是通过原始指针、new
和delete
执行手动内存管理。这样您就可以避免此类问题。
关于c++ - 清除 map 和删除内容的最简洁方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16364302/