I was trying to implement Prim's algorithm(eager) which requires to keep a track of best incoming edge(least cost) to a vertex. For this I use stl map as:
std::map<int, Edge*> bestEdgeFor;
However when I try to assign an edge to some key, what is actually stored is an edge with garbage values for the data members. As such I get some random edges as output. However when I assign a new instance of Edge class with same data, it works correctly.
bestEdgeFor[destNode] = &e; //Doesn't work
bestEdgeFor[destNode] = new Edge(e.from,e.to,e.cost); // Works
Here is the Edge class definition:
class Edge {
public:
int from;
int to;
int cost;
};
What exactly is the problem I am not able to figure out. Is it that we can't directly assign an object of a class? Please excuse my naivety.
This is the Graph class and I am doing the assignment operation in a member function of this class. e
comes from the adjList
. Is the scope valid?
class Graph {
int V;
std::map<int, std::list<Edge>> adjList;
map<int, Edge*> bestEdgeFor;
public:
void relaxEdgesAtNode(int currentNode, MinIndexedPQ& ipq, int* visited){
visited[currentNode] = 1;
for(Edge e : adjList[currentNode]) {
int destNode = e.to;
if(visited[destNode]){
continue;
}
if(!ipq.contains(destNode)) {
ipq.insert(destNode,e.cost);
// bestEdgeFor[destNode] = &e // Don't work
bestEdgeFor[destNode] = new Edge(e.from,e.to,e.cost); // Works
} else {
if(e.cost < ipq.keyOf(destNode)) {
ipq.decreaseKey(destNode,e.cost);
// bestEdgeFor[destNode] = &e // Don't work
bestEdgeFor[destNode] = new Edge(e.from,e.to,e.cost);
}
}
}
}
std::vector<Edge*> primsMST() {
int s = 0; //choosing the starting node
int* visited = new int[V]{0};
MinIndexedPQ ipq(V);
visited[s] = 1; // marking the starting node visited
int m = V - 1;
int edgeCount = 0, mstCost = 0;
std::vector<Edge*> mstEdges; // This is the return value in case the mst exists
// Call the problematic function
relaxEdgesAtNode(s, ipq, visited);
// Here, the values are garbage, and the printing code prints garbarge
}
};