STL priority_queue的自定义分配器

问题描述 投票:0回答:2

我试图将自定义分配器传递给STL的priority_queue。我已经能够为STL的vectorunordered_map这样做了,但是不能对priority_queue使用类似的语法。任何人都有我可以使用的提示或示例代码?

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

谢谢

c++ stl priority-queue
2个回答
1
投票

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

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

0
投票

std::priority_queue是一个容器适配器。它不会自己分配任何东西,它会将它推迟到底层容器(默认情况下,它是带有默认分配器的std::vector)。另见https://en.cppreference.com/w/cpp/container/priority_queue

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

© www.soinside.com 2019 - 2024. All rights reserved.