vector的resize(),reserve()把我搞的晕头转向,老是记不住。现在把自己的一点理解记录在这里。
先看看http://www.cplusplus.com/reference/vector/vector/resize/
std::vector::resize
void resize (size_type n, value_type val = value_type());
Change size
Resizes the container so that it contains n elements.
If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized.
If n is also greater than the current container capacity, an automatic reallocation of the allocated storage space takes place.
Notice that this function changes the actual content of the container by inserting or erasing elements from it.
resize()的作用是改变vector中元素的数目。
如果n比当前的vector元素数目要小,vector的容量要缩减到resize的第一个参数大小,既n。并移除那些超出n的元素同时销毁他们。
如果n比当前vector元素数目要大,在vector的末尾扩展需要的元素数目,如果第二个参数val指定了,扩展的新元素初始化为val的副本,否则按类型默认初始化。
注意:如果n大于当前的vector的容量(是容量,并非vector的size),将会引起自动内存分配。所以现有的pointer,references,iterators将会失效。
百度知道找到的一个关于resize和reserve的生动的例子:点这里
resize(),设置大小(size);
另外这位博友的blog写的也很清楚,请参考!《c++ vector resize & reserve》
好了,就到这里!