Jerome
Jerome

Reputation: 11

insert into priority_queue in constructor

I would like to make an object, called an Edge, which inserts itself into a priority_queue from its constructor. That is;

Class Edge {
   int m_from;
   int m_to;
   int m_cost;
public:
   edge(from, to, cost) : m_from(from), m_to(to), m_cost(cost) {
      edges.push(this);
}

The difficulty is the usual chicken-vs-egg problem. edges is a priority_queue of Edges, so it needs to know what an Edge is. Plus, it needs to have operator less-than overloaded for Edges, so that operator needs to be defined before I can instantiate the priority-queue, but it can't be defined because Edge hasn't been defined. I have tried it a bunch of different ways, but nothing works. Of course, I can just push the Edge in the code that calls the constructor,

edges.push(Edge(from,to,cost));

But it seems like there should be a way to enforce this. Basically, I am saying that these objects need to go on the priority_queue when created, so let's guarantee that happens.

Upvotes: 1

Views: 112

Answers (1)

Arunprasad Rajkumar
Arunprasad Rajkumar

Reputation: 1454

/* In .h*/

class Edge {
    int m_from;
    int m_to;
    int m_cost;
    static priority_queue<Edge*> edges;        
public:
    Edge(from, to, cost) : m_from(from), m_to(to), m_cost(cost) {
        edges.push(this);
    }
}

bool operator < (const Edge* first, const Edge* second) { return first->m_cost < second->m_cost; }

/*In .cpp */
priority_queue<Edge*> Edge::edges;

Upvotes: 3

Related Questions