samanca
samanca

Reputation: 153

Custom allocator for STL priority_queue

I am trying to pass a custom allocator to STL's priority_queue. I've been able to do so for STL's vector and unordered_map, but cannot use similar syntax for priority_queue. Anyone has a hint or sample code I can use?

Note that I need to pass an instance of the allocator as one of the constructor's arguments.

Thank you

Upvotes: 0

Views: 872

Answers (2)

Unlike std::vector and std::unordered_map, which are containers, std::priority_queue is a container adaptor. It contains a container and provides special access it to. Looking at suitable reference, you can see that the second template parameter of std::priority_queue is a container (std::vector by default). So you just need to pass your own container with a custom allocator:

std::priority_queue<T, std::vector<T, MyAllocator>> q;

Upvotes: 1

Max Langhof
Max Langhof

Reputation: 23691

std::priority_queue is a container adaptor. It doesn't allocate anything by itself, it defers that to the underlying container (which, by default, is std::vector with the default allocator). See also https://en.cppreference.com/w/cpp/container/priority_queue

In other words: To use a custom allocator, you have to specify a container (probably std::vector) that uses your custom allocator as the Container template argument of std::priority_queue. Then you can use any of the std::priority_queue constructors that accepts an allocator instance.

Upvotes: 0

Related Questions