How to preallocate(reserve) a priority_queue<vector>?

Yes, there's a constructor for that. It's slightly tedious that you also have to 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 the protected member, but I wouldn't recommend it.


Another solution might be to make your own class derived from std::priority_queue, such as:

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 a MyPQueue object in this way:

MyPQueue mpq(1024);

which object can be upcasted back to the base class whenether needed.

std::priority_queue<unsigned char, std::vector<unsigned char>>& pq = mpq;