priority_queue with pointers to objects

[b][red]This message was edited by karcirate at 2006-5-10 21:37:54[/red][/b][hr]
Is there a way to use a priority_queue with pointers instead of just passing objects? I want to be able to modify items in the queue that are not on top by saving their addresses before pushing them.
I tried it, and they get pushed and popped ok, but the Q doesn't seem to be sorting them according to the operator< function I defined.

[code]class thing
{
public:
thing(int i) {p=i;}
int p;
bool operator< (const thing& b) {return (this->p < b.p);}
};

priority_queue pq

thing t(2);
thing t1(5);
thing t2(8);
thing* tp[3];
tp[0]=&t;
tp[1]=&t1;
tp[2]=&t2;

pq.push(tp[1]);
pq.push(tp[0]);
pq.push(tp[2]);

//now if I output the queue starting at the top and popping as I go, it comes out in the same order I put it in. 8,2,5


[/code]

Comments

  • You don't want to push pointers to the container.
    Use an array of pointers as you did in the first example.

    The elements should be sorted correctly, but perhaps you want
    them in a different order? The default comparation used is
    "less", you will get the elements as 8, 5, 2.
    If you want them as 2, 5, 8, change the comparation object
    as in this example:

    [code]
    #include
    #include
    #include

    using namespace std;

    class thing
    {
    public:
    thing(int i)
    {
    p=i;
    }

    int p;

    bool operator < (const thing& obj) const
    {
    return this->p < obj.p;
    }

    bool operator > (const thing& obj) const
    {
    return this->p > obj.p;
    }
    };

    int main()
    {
    priority_queue, less > pq;
    /*
    for reverse order, use:
    priority_queue, greater > pq;
    */

    thing t0(2);
    thing t1(5);
    thing t2(8);

    thing* tp[3];
    tp[0]=&t0;
    tp[1]=&t1;
    tp[2]=&t2;

    cout << tp[0]->p << endl;
    cout << tp[1]->p << endl;
    cout << tp[2]->p << endl;
    cout << endl;

    pq.push(t0);
    pq.push(t1);
    pq.push(t2);

    cout << pq.top().p << endl;
    pq.pop();
    cout << pq.top().p << endl;
    pq.pop();
    cout << pq.top().p << endl;
    pq.pop();

    return 0;
    }
    [/code]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion