STL priority_queue 的自定义分配器
Posted
技术标签:
【中文标题】STL priority_queue 的自定义分配器【英文标题】:Custom allocator for STL priority_queue 【发布时间】:2018-09-13 08:14:52 【问题描述】:我正在尝试将自定义分配器传递给 STL 的priority_queue
。我已经能够为 STL 的vector
和unordered_map
这样做,但不能对priority_queue
使用类似的语法。谁有我可以使用的提示或示例代码?
请注意,我需要将分配器的一个实例作为构造函数的参数之一传递。
谢谢
【问题讨论】:
请注意,例如std::vector
和 std::unordered_map
是实际的容器。 std::priority_queue
是 container adaptor,它以特定方式使用其他容器。
【参考方案1】:
与std::vector
和std::unordered_map
是容器不同,std::priority_queue
是容器适配器。它包含一个容器并提供对其的特殊访问。查看合适的reference,可以看到std::priority_queue
的第二个模板参数是一个容器(默认std::vector
)。所以你只需要使用自定义分配器传递你自己的容器:
std::priority_queue<T, std::vector<T, MyAllocator>> q;
【讨论】:
稍作修改即可工作:std::priority_queue<T, std::vector<T, MyAllocator>, std::less<T>> q(compare, container);
谢谢大家! :)【参考方案2】:
std::priority_queue
是一个容器适配器。它自己不分配任何东西,它将分配给底层容器(默认情况下,它是std::vector
,带有默认分配器)。另见https://en.cppreference.com/w/cpp/container/priority_queue
换句话说:要使用自定义分配器,您必须指定一个使用自定义分配器的容器(可能是std::vector
)作为std::priority_queue
的Container
模板参数。然后,您可以使用任何接受分配器实例的std::priority_queue
构造函数。
【讨论】:
以上是关于STL priority_queue 的自定义分配器的主要内容,如果未能解决你的问题,请参考以下文章