I have a project where I’m implementing Dijkstra’s shortest path algorithm using C++ classes. It uses OpenGL but that is surely separate from my problems. I need some insight on what I’m doing wrong in my Dijkstra class method. Here is my relevant code:
class Node {
public:
GLfloat x, y, z;
int numLinks;
Node *link1;
Node *link2;
GLfloat distance;
Node *previous;
Node(GLfloat x, GLfloat y, Node *link1, Node *link2);
Node(GLfloat x, GLfloat y, Node *link1);
Node();
Node(GLfloat x, GLfloat y);
~Node();
bool dijkstra(Node* graph[], Node *source, Node *target); //returns true if a path to target is found
int dist(Node &n1, Node &n2);
};
int Node::dist(Node &n1, Node &n2) {
GLfloat d = sqrt((pow((n2.x - n1.x), 2)) + (pow((n2.y - n1.y), 2)));
return d;
}
bool Node::dijkstra(Node* graph[], Node *source, Node *target) {
queue<Node> q;
int i;
for (i = 0; i < NUM_NODES; i++) {
graph[i]->distance = INFIN;
}
source->distance = 0;
i = 0;
q.push(*source);
while (!q.empty()) {
Node temp = q.front();
GLfloat d1 = dist(temp, temp->link1);
GLfloat d2 = dist(temp, temp->link2);
temp.link1.distance = d1;
temp.link1.distance = d2;
GLfloat alt = temp.distance + temp->link1.distance;
if (alt < temp->link1.distance) {
temp->link1.distance = alt;
temp->previous = temp;
}
alt = temp->distance + temp->link2->distance;
if (alt < temp->link2->distance) {
temp->link2->distance = alt;
temp->previous = temp;
}
if(d1 > d2) {
q.push(temp->link2);
q.push(temp->link1);
} else {
q.push(temp->link1);
q.push(temp->link2);
}
q.pop();
i++;
}
return true;
}
My guess is that I’m using “->” and “.” operators all wrong. I get a lot of these errors when I try to compile:
error: base operand of ‘->’ has non-pointer type ‘Node’
My implementation of Dijkstra’s algorithm is somewhat retrofitted to meet my needs and is probably wrong, but I need this to compile so I can debug it.
The code listed is the only code giving me grief but if you would like to see another part of it just ask. A good explanation of what im doing wrong will be greatly appreciated.
You should use the ‘->’ operator when accessing data through a pointer. Otherwise you should use the ‘.’ opearator.
For example these following lines are identical
As for your compilation problems, the problem is with how you are accessing temp. temp is declaired as
Which means that temp is a copy of the node at the front of the queue and is not a pointer to it. This is why the compiler is complaining when you attempt to access it like it is a pointer. For example:
should look like
because temp is not a pointer but link1 is.