I have a class Node that, in addition to storing data, has a pointer to its parent Node. I store some Nodes in a priority_queue and overrode the < operator for comparison.
class Node {
public:
string name;
Node *parent;
int cost;
};
static bool operator<(const Node& lhs, const Node& rhs) {
return lhs.cost < rhs.cost;
}
priority_queue<Node> queue;
The problem is, the parent pointers seem to be messed up. My guess is, that when I pop a Node from the queue, the Nodes are actually moved up in memory and the pointers point to wrong Nodes. Could this be?
I tried to use a priority_queue of Node* pointers instead (and create them with new), so that only the pointers are reordered, not the objects themselves. This seems to fix the pointer issue, however now the queue is ordered by memory adress, and not the cost of the Nodes.
How can I implement a priority_queue that has objects pointing to each other?
Use
Node*and a custom comparator for your queue. With what you currently have, you can do the following, though i suggest you use smart pointers if they’re available in your current toolchain.Alternatively, for a more local-defintiion of the comparator, you can stuff the compare-my-pointer class within
Nodeso as not to pollute the global namespace:Regarding pointers being “messed up”, with object-level storage (as opposed to pointer-storage as above) your priority queue can/will move elements around each time it re-heapifies the content after a pop (in case you weren’t aware, the standard lib uses a heap structure for a priority queue by default).
Finally, I leave the notion of how to deal with a parent-pointer of some node being popped prior to any/some of its children, being deleted, and thereby creating an invalid pointer to any children left in the queue to you, but it sounds like you’re aware that can happen.