问题描述
在处理向量时使用 Reserve 有什么好处.我应该什么时候使用它们?无法找到明确的答案,但我认为在使用它们之前提前预订会更快.
What is the benefit of using reserve when dealing with vectors. When should I use them? Couldn't find a clear cut answer on this but I assume it is faster when you reserve in advance before using them.
怎么说你们比我聪明?
推荐答案
如果您知道向量最终将包含多少个元素,这很有用 - 它可以帮助向量避免重复分配内存(并且必须将数据移动到新的记忆).
It's useful if you have an idea how many elements the vector will ultimately hold - it can help the vector avoid repeatedly allocating memory (and having to move the data to the new memory).
一般来说,这可能是您不需要担心的潜在优化,但它也无害(最坏的情况是,如果您高估,最终会浪费内存).
In general it's probably a potential optimization that you shouldn't need to worry about, but it's not harmful either (at worst you end up wasting memory if you over estimate).
当您希望确保现有迭代器不会因添加新元素而失效时,它可以不仅仅是优化的一个领域.
One area where it can be more than an optimization is when you want to ensure that existing iterators do not get invalidated by adding new elements.
例如,push_back()
调用可能会使向量的现有迭代器无效(如果发生重新分配).但是,如果您保留了足够多的元素,则可以确保不会发生重新分配.不过,这是一种不需要经常使用的技术.
For example, a push_back()
call may invalidate existing iterators to the vector (if a reallocation occurs). However if you've reserved enough elements you can ensure that the reallocation will not occur. This is a technique that doesn't need to be used very often though.
这篇关于在向量中使用 Reserve() 的好处 - C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!