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

后端 未结 4 1473
暗喜
暗喜 2021-02-10 07:23

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 random

相关标签:
4条回答
  • 2021-02-10 07:58

    I would follow the example set by some of the other container adapters in the standard library use composition and make the type of the underlying container a template parameter. Though since it is a school project that might be too much flexibility. You might start by using composition with one of the existing Containers and build from there if necessary.

    0 讨论(0)
  • 2021-02-10 08:19

    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
    };
    
    0 讨论(0)
  • 2021-02-10 08:21

    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.

    0 讨论(0)
  • 2021-02-10 08:24

    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).

    0 讨论(0)
提交回复
热议问题