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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With