I am trying to delete references to unordered_map
element. The part of my classes responsible for that looks like this:
class Edge:
{
public:
Node* from;
Node* to;
}
class Node:
{
public:
std::string name;
bool to_delete;
}
class Graph:
{
public:
std::unordered_map<std::string, Node> nodes;
std::vector<Edge> edges;
}
and in my main file code I am doing something like this:
Node n("My node");
graph.nodes.insert({n.name,n});
edge.from = &graph.nodes[n.name];
// Some other stuff
for(auto& edge : graph.edges)
{
if(edge.from->to_delete)
{
graph->nodes->erase(edge.from->name);
delete edge.from;
edge.from = NULL;
}
if(edge.to->to_delete)
{
graph->nodes->erase(edge.to->name);
delete edge.to;
edge.to = NULL;
}
if(edge->from && edge->to)
DoSomethingWithNodes(edge->from, edge->to);
else
removeEdge(edge);
}
Currently I am deleting pointers based on this answer but I am getting segmentation error on line with delete
. In this same answer there is also suggestion to use smart pointers
. I am not sure about using here shared_ptr. I have option here, that multiple edges will have pointers to one node object, but what will actually happen when I'll erase
node from graph's unordered_map. Will I get false for last if/else condition if it was pointing there? I don't fully understand that.
EDIT:
Assume that I want to display the name of a node before it gets deleted. So I'll have something like that:
for(auto& edge : graph.edges)
{
if(edge.from->to_delete)
{
printf("Node to delete: %s",edge.from->name.c_str());
graph->nodes->erase(edge.from->name);
edge.from = nullptr;
}
if(edge.to->to_delete)
{
printf("Node to delete: %s",edge.to->name.c_str());
graph->nodes->erase(edge.to->name);
edge.to = nullptr;
}
if(edge->from && edge->to)
DoSomethingWithNodes(edge->from, edge->to);
}
Right now, there is no protection against null pointers, because as I've experienced edge.from->to_delete
is somehow, sometimes returning true. What I've tried is changing if conditions to:
if(edge.from && edge.from->to_delete)
but it doesn't help at all.