class Edge;
class Node
{
public:
Node(): distance(numeric_limits<double>::infinity()), visited(false) {}
Node(string a_id): distance(numeric_limits<double>::infinity()), visited(false), id(a_id) {}
bool operator==(const Node& p) {return p.id == id; }
string id;
double distance;
bool visited;
string previous;
vector<Edge*> edges;
};
class Edge
{
public:
Edge(double weight, string id)
{
this->weight = weight;
dest = new Node(id);
}
double weight;
Node * dest;
};
class Comparator {
public:
bool operator()(const Node* a, const Node* b)
{
return (a->distance > b->distance);
}
};
These are my classes. I created a priority queue from vector of node pointers:
priority_queue<Node*, vector<Node*>, Comparator > queue;
But after some operations I get segmentation fault.
queue.push(nodes[0]);
queue.pop();
queue.push(nodes[1]);
queue.push(nodes[4]);
queue.pop();
queue.push(nodes[3]);
queue.push(nodes[5]);
queue.pop();
queue.push(nodes[6]);
queue.push(nodes[7]);
nodes[6]->distance=1;
queue.pop();
At the last line
queue.pop();
I get an segmentation fault and I don't get it why it happens. Thanks in advance.
I added
#include <limits>
#include <queue>
#include <string>
#include <vector>
using namespace std;
to the top of your file and used the following main():
int main(int argc, char* argv[])
{
priority_queue<Node*, vector<Node*>, Comparator > queue;
vector<Node> vnode(10);
vector<Node*> nodes(10);
for (int i = 0; i < 10; ++i)
{
vnode[i].distance = i;
nodes[i] = &vnode[i];
}
queue.push(nodes[0]);
queue.pop();
queue.push(nodes[1]);
queue.push(nodes[4]);
queue.pop();
queue.push(nodes[3]);
queue.push(nodes[5]);
queue.pop();
queue.push(nodes[6]);
queue.push(nodes[7]);
nodes[6]->distance=1;
queue.pop();
}
It compiles and runs without a segfault, so I'm guessing your nodes aren't all initialized? Also, the line nodes[6]->distance=1;
didn't cause node 6 to pop()
next; it still popped node 4 there, but then reordered the rest of the queue with node 6 first, then 5, then 7.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.