STL 的自定义分配器 priority_queue

Custom allocator for STL priority_queue

我正在尝试将自定义分配器传递给 STL priority_queue。我已经能够对 STL 的 vectorunordered_map 这样做,但不能对 priority_queue 使用类似的语法。谁有我可以使用的提示或示例代码?

请注意,我需要将分配器的实例作为构造函数的参数之一传递。

谢谢

std::priority_queue 是容器适配器。它自己不分配任何东西,它将分配给底层容器(默认情况下,默认分配器为 std::vector)。另见 https://en.cppreference.com/w/cpp/container/priority_queue

换句话说:要使用自定义分配器,您必须指定一个容器(可能 std::vector),该容器使用您的自定义分配器作为 std::priority_queueContainer 模板参数。然后,您可以使用任何接受分配器实例的 std::priority_queue 构造函数。

std::vectorstd::unordered_map不同,它们是容器,std::priority_queue是容器适配器。它包含一个容器并提供对其的特殊访问。查看合适的reference,可以看到std::priority_queue的第二个模板参数是一个容器(默认为std::vector)。所以你只需要用自定义分配器传递你自己的容器:

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