Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending the std::priority_queue functionality

Tags:

c++

stl

I would like to implement a priority queue in such a way that every time I push a new item or pop an item from the queue a function is executed, for example add or subtract each items "error" to the global "error".

Is there some neat standard way to achieve this? Below is a simplified example where I have solved it be having a struct that "wraps" the std::priority_queue. I'm a novice C++ programmer and hence I'm not sure if this is the most efficient solution.

#include <queue>

struct myStruct {
    double Error;
    friend bool operator<(const myStruct& lhs, const myStruct& rhs)
    {
        return lhs.Error < rhs.Error;
    }
};

typedef std::priority_queue < myStruct, std::vector<myStruct>, std::less<myStruct>> StdQueue;

struct priorityQueue {
    priorityQueue() { Error = 0; }
    StdQueue queue;
    double Error;

    void push(myStruct s)
    {
        Error += s.Error;
        queue.push(s);
    }

    void pop()
    {
        Error -= queue.top().Error;
        queue.pop();
    }
};

Thanks in advance!

like image 244
DoubleTrouble Avatar asked Aug 23 '26 08:08

DoubleTrouble


1 Answers

Unlike actual containers the container adaptors are actually designed to be inheritable. For example, if you look at e.g. this std::priority_queue reference you will see that it has protected member objects.

That means you can inherit from std::priority_queue and create your own pop and push functions to do what you want before calling the actual queues functions.

As noted by skypack in a comment the functions are not virtual, which means you can't use polymorphism with your inherited class. You can't really pass it to functions expecting a std::priority_queue, the code has to be explicitly use your class.

like image 53
Some programmer dude Avatar answered Aug 25 '26 20:08

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!