resize() 根据给定的大小添加/删除元素。 Reserve() 保留内存空间,并且不会重新分配内存。我的问题是调整大小是否也与矢量的容量一样,只是不会增加?
要添加,可以组合:
std::vector<X> vector;
vector.reserve(5);
vector.resize(5);
有什么意义吗?是多余的吗?这里的目标是能够覆盖向量中的值,而不让向量分配任何额外的空间。
From 这个网站 https://frogatto.com/2009/11/17/how-cs-vector-works-the-gritty-details/:
-
resize()
: This lets you change the size of the vector to any size you want.
-
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).
- 它不会限制缓冲区的大小。如果缓冲区空间不足,它将根据需要自动重新分配。
我的问题是调整大小是否也与
向量的容量只会增加吗?
要添加,将组合:
std::vector<X> vector;
vector.reserve(5);
vector.resize(5);
有什么意义吗?是多余的吗?
vector.reserve(5);
在这种情况下是多余的。
这里的目标是能够覆盖向量中的值而无需
让向量分配任何额外的空间。
对于这个目标,这取决于您想要如何覆盖这些值。
- 如果您打算直接按索引写入,那么您必须使用
resize()
.
- 如果您正在使用
push_back()
, then reserve()
会更好,这样你就可以避免创建X
twice.
请记住,用于自动预订的算法是实现定义的。看here https://stackoverflow.com/q/1742859/1460794有关性能方面的更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)