【发布时间】:2019-03-26 20:41:02
【问题描述】:
我有一个图表类
struct Graph
{
list<Node *> vertices;
};
int main()
{
Graph g;
// fill out graph
return 0;
}
我想执行一个 Dijkstra-shortest-path-like 算法。第 1 步是从所有节点中创建一个集合,我通过
完成set<Node *> outstanding;
for (auto itx=g.vertices.begin(); itx!=g.vertices.end(); itx++)
{
outstanding.insert(*itx);
}
第 2 步是提取具有特定属性的顶点
double max_height_comp = (*(g.vertices.begin()))->max_height;
set<Node *>::const_iterator it_max;
while (!outstanding.empty())
{
for (auto its=outstanding.begin(); its!=outstanding.end(); its++)
{
if ((*its)->max_height >= max_height_comp)
{
max_height_comp = (*its)->max_height;
it_max = its;
}
}
outstanding.erase(it_max);
我收到这些运行时错误
malloc: *** error for object 0x7fc485c02de0: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug
我担心erase() 在outstanding 的元素上调用free() 或delete,它们是指针。但它为什么要这样做呢?我只想从集合中删除指针的值,不想删除指针指向的数据。
【问题讨论】:
-
我怀疑您将迭代器擦除到同一个节点两次。你能在擦除之间显示你初始化
it_max和max_height_comp的代码吗? -
@PeterBell 感谢您的评论。我编辑了帖子。
-
所以让我们分解一下。您的循环所做的只是擦除集合中大于或等于
(*(g.vertices.begin()))->max_height;? 的最大项目。那是对的吗?如果是这样,这不需要for循环。可以使用std::max_element获得最大项目,并与max_height进行比较。如果是这样,请删除该迭代器。
标签: c++ pointers malloc stdset