Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ priority_queue underlying vector container capacity resize

I'm using priority_queue with a vector as an underlying container. However I expect the size of the heap to be very large. I'm aware of problems with dynamic vector capacity resize. So I'm looking for ways to initially allocate enough space for the underlying vector in my priority_queue. Are there any suggestions out there to achieve this?

Thanks

like image 854
cagribal Avatar asked Sep 08 '10 09:09

cagribal


1 Answers

stdlib container adaptors provide a "back door" to access the underlying container: the container is a protected member called c.

Therefore you can inherit from the adapter to gain access to the container:

#include <queue>
#include <iostream>

template <class T>
class reservable_priority_queue: public std::priority_queue<T>
{
public:
    typedef typename std::priority_queue<T>::size_type size_type;
    reservable_priority_queue(size_type capacity = 0) { reserve(capacity); };
    void reserve(size_type capacity) { this->c.reserve(capacity); } 
    size_type capacity() const { return this->c.capacity(); } 
};

int main()
{
    reservable_priority_queue<int> q;
    q.reserve(10000);
    std::cout << q.capacity() << '\n';
}

If you feel bad about inheriting from a stdlib class, use private inheritance and make all the methods of priority_queue accessible with using declarations.

like image 157
visitor Avatar answered Nov 03 '22 10:11

visitor