在向量中使用reserve()的好处-C ++ [英] Benefits of using reserve() in a vector - C++

查看:135
本文介绍了在向量中使用reserve()的好处-C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理向量时使用保留有什么好处。我什么时候应该使用它们?

什么比你更聪明呢? p>

解决方案

如果您知道向量最终将拥有多少个元素,这很有用-它可以帮助向量避免重复分配内存(并且



通常来说,这可能是一种潜在的优化,您无需担心,但也无害(在最糟糕的情况是,如果您过高估计,最终会浪费内存。)



要确保现有迭代器不会失效的一个领域,它可能比优化还重要。通过添加新元素。



例如, push_back()调用可能会使向量的现有迭代器无效(如果重新分配)。但是,如果您保留了足够的元素,则可以确保不会发生重新分配。这种技术虽然不需要经常使用。


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.

What say you people smarter than I?

解决方案

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.

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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆