本文介绍了C ++ priority_queue底层向量容器容量调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用priority_queue与向量作为底层容器。但我期望堆的大小非常大。我知道动态向量能力调整大小的问题。所以我正在寻找方法来初始分配足够的空间为底层向量在我的priority_queue。是否有任何建议可以实现?

I'm using priority_queue with a vector as an underlying container. However I expect the size of the heap to be very large. I'm aware of problems with dynamic vector capacity resize. So I'm looking for ways to initially allocate enough space for the underlying vector in my priority_queue. Are there any suggestions out there to achieve this?

感谢

推荐答案

stdlib容器适配器提供访问底层容器的后门:容器是一个受保护的成员 c

stdlib container adaptors provide a "back door" to access the underlying container: the container is a protected member called c.

因此,您可以继承适配器以访问容器:

Therefore you can inherit from the adapter to gain access to the container:

#include <queue>
#include <iostream>

template <class T>
class reservable_priority_queue: public std::priority_queue<T>
{
public:
    typedef typename std::priority_queue<T>::size_type size_type;
    reservable_priority_queue(size_type capacity = 0) { reserve(capacity); };
    void reserve(size_type capacity) { this->c.reserve(capacity); } 
    size_type capacity() const { return this->c.capacity(); } 
};

int main()
{
    reservable_priority_queue<int> q;
    q.reserve(10000);
    std::cout << q.capacity() << '\n';
}

如果你对从stdlib类继承感到不好,可以使用私有继承和make所有 priority_queue 的方法可以使用使用声明访问。

If you feel bad about inheriting from a stdlib class, use private inheritance and make all the methods of priority_queue accessible with using declarations.

这篇关于C ++ priority_queue底层向量容器容量调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 18:30