C++ 标准向量 resize() 函数 [英] C++ standard vector resize() function

查看:107
本文介绍了C++ 标准向量 resize() 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

resize() 根据给定的大小添加/删除元素.Reserve() 保留内存空间,它不会重新分配内存.我的问题是调整大小是否也与向量的容量相同,但不会增加?

要补充的是:

 std::vector向量;vector.reserve(5);矢量.resize(5);

有意义吗?是多余的吗?这里的目标是能够覆盖向量中的值,而无需向量分配任何额外空间.

解决方案

来自

<块引用>

我的问题是调整大小是否也与载体的容量只会不会增加?要添加,将组合:

 std::vector向量;vector.reserve(5);矢量.resize(5);

有意义吗?是多余的吗?

vector.reserve(5); 在这种情况下是多余的.

<块引用>

这里的目标是能够在不覆盖向量的情况下覆盖向量中的值让向量分配任何额外的空间.

对于这个目标,它取决于您想如何覆盖这些值.

  • 如果你打算直接通过索引编写,那么你必须使用resize().
  • 如果您使用的是 push_back(),那么 reserve() 会更好,这样您就可以避免创建 X 两次.立>

请记住,用于自动预订的算法是实现定义的.有关性能方面的更多信息,请参阅此处.

resize() adds/removes elements based on the size given to it. reserve() reserves memory space and it will not reallocate memory. The question I have is whether resize also works the same as in the capacity of the vector will only not increase?

To add, would a combination of:

 std::vector<X> vector;
 vector.reserve(5);
 vector.resize(5); 

make any sense? Is it redundant? The goal here is to be able to overwrite values in the vector without having the vector allocate any extra space.

解决方案

From this site:

  • resize(): This lets you change the size of the vector to any size you want.
    • It will fill the underlying buffer with elements.
  • reserve(): This changes the capacity of the vector. Note that this doesn’t change the vector’s size, it just changes the size of the underlying buffer, to give more room for expansion of the buffer before the buffer has to be resized. Unlike calling resize(), this doesn’t change the behavior of the program, just the performance (Subsequent use of the reserved space will not incur a performance penalty for incremental reservations).
    • It will not limit the size of the buffer. If the buffer runs out of space it will automatically reallocate as needed.

The question I have is whether resize also works the same as in the capacity of the vector will only not increase? To add, would a combination of :

 std::vector<X> vector;
 vector.reserve(5);
 vector.resize(5);

make any sense? Is it redundant?

vector.reserve(5); Would be redundant in this case.

The goal here is to be able to overwrite values in the vector without having the vector allocate any extra space.

For this goal it depends on how you want to overwrite the values.

  • If you are planning to write directly by index, then you must use resize().
  • If you are using push_back(), then reserve() would be better so that you can avoid creating X twice.

Keep in mind that the algorithm used for the automatic reservation is implementation defined. See here for more regarding the performance aspect.

这篇关于C++ 标准向量 resize() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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