How to predefine (reserve) priority_queue <vector>?
How can I pre-allocate std::priority_queue with a container of type std::vector ?
std::priority_queue<unsigned char, std::vector<unsigned char>> pq; pq.c.reserve(1024); It does not compile because the underlying vector is a protected member. Can the priority_queue constructor be used to wrap around a pre-reserved vector?
Yes, there is a constructor for this. It's a little tiring that you must also specify a comparator:
std::vector<unsigned char> container; container.reserve(1024); std::priority_queue<unsigned char, std::vector<unsigned char>> pq ( std::less<unsigned char>(), std::move(container)); You can also use evil shenanigans to access a protected member, but I would not recommend it.
Another solution could be to create your own class derived from std :: priority_queue, for example:
class MyPQueue : public std::priority_queue<unsigned char, std::vector<unsigned char>> { public: MyPQueue(size_t reserve_size) { this->c.reserve(reserve_size); } }; then in the code, create the MyPQueue object this way:
MyPQueue mpq(1024); which can be redirected back to the base class needed for use.
std::priority_queue<unsigned char, std::vector<unsigned char>>& pq = mpq; In general, in C++11 you can write the make_reserved function, as shown below.
#include <vector> #include <iostream> #include <utility> #include <functional> template <class T> std::vector<T> make_reserved(const std::size_t n) { std::vector<T> v; v.reserve(n); return std::move(v); } int main() { using Q = std::priority_queue<int, std::vector<int>>; auto q = Q(std::less<int>(), make_reserved<int>(100)); std::cout << q.size() << std::endl; }