简体   繁体   English

STL priority_queue的自定义分配器

[英]Custom allocator for STL priority_queue

I am trying to pass a custom allocator to STL's priority_queue . 我试图将自定义分配器传递给STL的priority_queue I've been able to do so for STL's vector and unordered_map , but cannot use similar syntax for priority_queue . 我已经能够对STL的vectorunordered_map ,但是不能对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 谢谢

Unlike std::vector and std::unordered_map , which are containers, std::priority_queue is a container adaptor. std::vectorstd::unordered_map是容器不同, std::priority_queue是容器适配器。 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). 查看合适的参考资料 ,您可以看到std::priority_queue的第二个模板参数是一个容器(默认为std::vector )。 So you just need to pass your own container with a custom allocator: 因此,您只需要使用自定义分配器传递自己的容器即可:

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

std::priority_queue is a container adaptor. std::priority_queue是容器适配器。 It doesn't allocate anything by itself, it defers that to the underlying container (which, by default, is std::vector with the default allocator). 它本身不会分配任何内容,而是将其推迟到基础容器(默认情况下,该容器是具有默认分配器的std::vector )。 See also https://en.cppreference.com/w/cpp/container/priority_queue 另请参阅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 . 换句话说:要使用自定义分配器,您必须指定一个容器(可能是std::vector ),该Container将自定义分配器用作std::priority_queueContainer模板参数。 Then you can use any of the std::priority_queue constructors that accepts an allocator instance. 然后,您可以使用任何接受分配器实例的std::priority_queue构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM