Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I preallocate a std::priority_queue with a container of type std::vector?

std::priority_queue<unsigned char, std::vector<unsigned char>> pq;
pq.c.reserve(1024);

Does not compile because the underlying vector is a protected member. Is it possible to use the constructor of the priority_queue to wrap it around a pre-reserved vector?

like image 554
Boyko Perfanov Avatar asked Mar 24 '15 15:03

Boyko Perfanov


1 Answers

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.

like image 192
Mike Seymour Avatar answered Sep 30 '22 20:09

Mike Seymour