我正在尝试实现Dijkstra算法。为此,我使用一个优先级队列存储指向该类对象的节点的指针' Node'它将返回到起始节点的距离最小的节点。我减少了代码,以便手动编辑起始节点和当前节点之间的距离,并从优先级队列中提取元素。通常Dijkstra会这样做。以下代码无法正常运行:
using namespace std;
#include <iostream>
#include <limits>
#include <vector>
#include <queue>
const int numberNodes = 6;
int IMAX = numeric_limits<int>::max();
class Node{
public:
Node(float pdistance, int pid){distance = pdistance; id = pid;}
float distance;
int id; //only for debug
};
Node** nodes; //in int main() Array of Node*
class Compare{ //Compare pointer to nodes based on distance to start node (Dijkstra)
public:
bool operator() (Node *n1, Node *n2) const {
return n1->distance>n2->distance;
}
};
priority_queue<Node*, vector<Node*>, Compare> pq;
int main(){
nodes = new Node*[numberNodes];
for(int i=0; i<numberNodes; i++){ //create new objects and store them in pq
nodes[i] = new Node(IMAX, i);
pq.push(nodes[i]);
}
Node* sNode; //Start node. not contained in nodes[]
sNode = new Node(0, -1); //distance 0, id -1
pq.push(sNode);
cout << "extracted: Node " << (pq.top())->id << " , distance " << (pq.top())->distance << endl;
pq.pop();
nodes[0]->distance = 0.5;
nodes[1]->distance = 0.5;
cout << "extracted: Node " << (pq.top())->id << " , distance " << (pq.top())->distance << endl;
pq.pop();
cout << "extracted: Node " << (pq.top())->id << " , distance " << (pq.top())->distance << endl;
pq.pop();
nodes[2]->distance = 2.5;
nodes[3]->distance = 3.5;
cout << "extracted: Node " << (pq.top())->id << " , distance " << (pq.top())->distance << endl;
pq.pop();
}
它返回:
extracted: Node -1 , distance 0
extracted: Node 0 , distance 0.5
extracted: Node 1 , distance 0.5
extracted: Node 5 , distance 2.14748e+09
pq正常工作三次,但最后它应该返回节点2,距离为2.5。
那我怎么能让它发挥作用呢?
感谢您的回答
答案 0 :(得分:1)
由于你弹出了priority_queue的元素,它的大小正在减少,因为这行:
节点[2] - &gt;距离= 2.5; nodes [3] - &gt; distance = 3.5;
应改为:
nodes [0] - &gt;距离= 2.5; nodes [1] - &gt; distance = 3.5;
答案 1 :(得分:0)
在顶部,变量numberNodes设置为等于6。 将它减少到一个较小的数字,因为它正在初始化主函数中的6个节点。
庞大的数字是编译器初始化浮点数的默认垃圾,因为你声明它但没有为它分配任何内容。
要避免此问题,请确保在使用之前初始化所有变量。
for(int i=0; i<numberNodes; i++){ //create new objects and store them in pq
nodes[i] = new Node(IMAX, i);
nodes[i].distance = 0.0f; //<--set a default value
pq.push(nodes[i]);
}