c++ vector resize()和reserve()区别

  resize()是改变了size和capacity

void resize ( size_type sz, T c = T() );

Change size
Resizes the vector to contain sz elements.

If sz is smaller than the current vector size, the content is reduced to its first sz elements, the rest being dropped. 如果sz小于现在的尺寸,内容减小到sz,其余 部分丢弃。

If sz is greater than the current vector size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. This may cause a reallocation.
sz大于现在的尺寸,内容扩大。(原来的内容还在)。

reserve改变了capacity。
void reserve ( size_type n );
Request a change in capacity
 
Requests that the vector capacity be at least enough to contain n elements.

vector 的reverse只是增加了vector的capacity,但是size没有改变!
resize同时改变了vector的capacity和size!

reserve是容器预留空间,但并不真正创建元素对象,在创建对象之前,不能引用容器内的元素,因此当加入新的元素时,需要用push_back()/insert()函数。

 

原文地址:https://www.cnblogs.com/youxin/p/2566186.html