我在AI中试图清理我用于A*搜索的无序地图中的内存,下面的代码是我正在为我的一个地图所做的。我不能让它工作,我需要一些帮助。
for (std::unordered_map<Tile*, PlannerNode*>::iterator itr = plan_map.begin(); itr != plan_map.end(); ++itr)
{
delete itr;
itr->second = nullptr;
}发布于 2017-12-02 11:14:01
因为你有一个指针的unordered_map,你需要释放它们所指向的空间,也就是在它们上调用delete。之后,您希望从映射中对它们执行erase操作,而不是将它们设置为nullptr。下面的示例可能会对您有所帮助。它将打印出来
Destroying Tile
Destroying PlannerNode在你的屏幕上。
#include <iostream>
#include <unordered_map>
struct Tile {
~Tile() { std::cout << "Destroying Tile\n"; }
};
struct PlannerNode {
~PlannerNode() { std::cout << "Destroying PlannerNode\n"; }
};
int main()
{
std::unordered_map<Tile*, PlannerNode*> plan_map;
plan_map.emplace(new Tile, new PlannerNode);
for (auto itr = plan_map.begin(); itr != plan_map.end(); /* no increment here! */)
{
delete itr->first;
delete itr->second;
itr = plan_map.erase(itr);
}
}使用RAII结构来管理指针可能会更好,例如std::unique_ptr。这样,您就可以让plan_map超出作用域,所有内存都会自动为您清除。
std::unordered_map<std::unique_ptr<Tile>, std::unique_ptr<PlannerNode>> plan_map;
plan_map.emplace(std::make_unique<Tile>(), std::make_unique<PlannerNode>());发布于 2017-12-02 11:49:58
std::for_each(plan_map.begin(), plan_map.end(), [](auto& p){delete p.first; delete p.second;});
plan_map.clear();这是一种更干净的方式,也避免了笨拙的迭代器。理解lambda语法不在这个问题的讨论范围内,我建议您通过查阅C++ lambda来理解这一点。
一定要研究一下std::unique_ptr<>,这会对你有所帮助,你需要做的就是,plan_map.clear();
参考:http://en.cppreference.com/w/cpp/algorithm/for_each
https://stackoverflow.com/questions/47604017
复制相似问题