Benefits of using reserve() in a vector - C++(在向量中使用 Reserve() 的好处 - C++)
问题描述
在处理向量时使用 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在向量中使用 Reserve() 的好处 - C++
基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
