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?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
stdlib 容器适配器提供了一个“后门”来访问底层容器:该容器是一个名为
c
的受保护成员。因此,您可以从适配器继承来访问容器:
如果您对从 stdlib 类继承感到不舒服,请使用私有继承并使用
using
使priority_queue
的所有方法都可访问代码>声明。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:
If you feel bad about inheriting from a stdlib class, use private inheritance and make all the methods of
priority_queue
accessible withusing
declarations.您无法直接访问底层容器来修改容量。不过,您可以将内部使用的容器更改为
std::deque
。 std::deque 容器可能比向量稍慢(不是用大 O 表示法),但增长速度要快得多,因为它不需要重新定位所有现有元素。You cannot directly access the underlying container to modify the capacity. You can however change the container that is used internally to a
std::deque
. Thestd::deque
container might be slightly slower (not in big-O notation) than a vector, but growing it is much faster as it does not need to relocate all existing elements.使用
reserve
函数:示例:
Use
reserve
function:Sample:
大卫在对阿列克谢的回答的评论中是正确的:矢量实现不太可能分配副本上保留的内容。因此,要么提供自己的容器来执行此操作,要么继承priority_queue并提供一些成员来使用底层容器。
David is right in his comment to Alexey's answer: there's not much chance the vector implementation will allocate what is reserved on a copy. So either provide your own container that does do this, or inherit from priority_queue and provide some members to play with the underlying container.
正如 David 所建议的,使用 std::deque 可能是一个很好的解决方案。内存块足够小,通常允许您在队列增长时保留大部分内存。
然而,这只是一个更安全的解决方案,而不是一个安全的解决方案。
如果你不太关心效率,你可以使用 stlxxl ,它是标准模板库的实现对于超大数据集。这样,可分配的内存将是您的整个硬盘驱动器(该库还支持多个硬盘驱动器或网络驱动器)。
As suggest David, using a std::deque is probably a good solution. The memory chunks are small enough to usually allow you to reserve most of your memory while the queue is growing.
However it is just a more secure solution but not a safe solution.
If you don't care too much about efficiency you can use stlxxl wich is an implementation of the Standard Template Library for Extra Large Data Sets. This way the allocatable memory will be your entire harddrive (the library also support multiple harddrives or network drives).