我有两个节点指针向量。
vector<Node*> tmp;
vector<Node*> nodes;
我说tmp = nodes;
如果 I delete nodes
, thentmp
也被删除。
有什么方法可以tmp
在修改时不进行nodes
修改,例如将其设为 const?
我基本上在运行 Dijkstra's。但该算法在确定最短路径时总是删除节点向量。这意味着我只能做一次从源到目的地的最短路径。
如果我有一个图表 0--->1--->2--->3 即
CGraph g;
g.Dijkstras(0);
g.PrintShortestRouteTo(2);
g.Dijktras(2);
g.PrintShortestRouteTo(3); <-- source is still 0 since nodes is deleted
therefore I get the path from 0 to 2
class Node
{
public:
Node(int id)
: id(id), previous(NULL),
distanceFromStart(INT_MAX)
{
nodes.push_back(this);
}
public:
int id;
Node* previous;
int distanceFromStart;
};
vector<Node*> nodes;
void CGraph::Dijkstras(int source)
{
nodes[source]->distanceFromStart = 0;
for (int i = 0; i < (int)nodes.size(); i++)
cout << nodes[i]->distanceFromStart << " " ;
cout << "------------------------" << endl;
while (nodes.size() > 0)
{
Node* smallest = ExtractSmallest(nodes);
//cout << "Smallest: " << smallest->id << " ";
//Node* smallest = nnodes[1];
vector<Node*>* adjacentNodes =
AdjacentRemainingNodes(smallest);
const int size = adjacentNodes->size();
for (int i=0; i<size; ++i)
{
Node* adjacent = adjacentNodes->at(i);
int distance = Distance(smallest, adjacent) +
smallest->distanceFromStart;
if (distance < adjacent->distanceFromStart)
{
adjacent->distanceFromStart = distance;
adjacent->previous = smallest;
}
}
delete adjacentNodes;
}
}