Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a priority queue that can be iterated over in C++

I need to implement a priority queue for a project, but the STL's priority_queue is not indicated since we need to iterate over all elements and remove them randomly.

We are thinking about using the STL's set for this, wrapping it in a class to make it an ADT.

Is there a smarter solution for this?

How can we make it so some of set's public member functions can be used publicly? We're interested in iterators, etc.

Apparently deriving the STL is unwise because of the lack of virtual destructors :/


New code:

#ifndef PRIORITYQUEUE_H_
#define PRIORITYQUEUE_H_

#include <set>

template<typename T, template<typename X> class impl_type = std::set>
class PriorityQueue {
    typedef impl_type<T> set_type;
    typedef typename set_type::iterator iterator;
public:
    void push(const T& x) {
        insert(x);

    }

    void pop() {
        erase(begin());
    }

    const T& top() const {
        return *begin();
    }
};

#endif /* PRIORITYQUEUE_H_ */

So, we currently have this. The compiler doesn't complain about insert, but it does complain about erase(begin()) and return *begin():

there are no arguments to 'begin' that depend on a template parameter, so a declaration of 'begin' must be available

Why is this?

like image 789
F. P. Avatar asked Dec 12 '10 12:12

F. P.


3 Answers

Do you really need a priority queue ?

You need iterate over all items and remove randomly -> linked list

If you need to keep the list sorted, sort it at the beginning and then, when inserting new item, use insertion sort (insert new item on right place).

like image 166
Vojta Avatar answered Nov 17 '22 13:11

Vojta


You should be able to implement your own priority queue using std::vector, std::make_heap, std::push_heap, and std::pop_heap. Isn't this how std::priority_queue is implemented? You'll just need to call std::make_heap again to fix the data structure when you remove a random element.

Do you need to iterate over the elements in order? There's a std::sort_heap algorithm to order the underlying std::vector.

like image 22
Blastfurnace Avatar answered Nov 17 '22 14:11

Blastfurnace


STL's set should be usable to make what you want, although I must note that the list of requirements looks a little strange. You could just define a new type.

template<typename T, template<typename X> class impl_type = std::set> class prio_queue {
    typedef impl_type<T> set_type;
    typedef typename set_type::iterator iterator;
    // etc
public:
    // Forward the set's members
    T& top() {
        return *begin();
    }
    // etc
};
like image 2
Puppy Avatar answered Nov 17 '22 12:11

Puppy