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);
reserve(),設置容量(capacity);
size()是分配容器的內存大小,而capacity()只是設置容器容量大小,但並沒有真正分配內存。
打個比方:正在建造的一輛公交車,車里面可以設置40個座椅(reserve(40);),這是它的容量,但並不是說它里面就有了40個座椅,只能說明這部車內部空間大小可以放得下40張座椅而已。而車里面安裝了40個座椅(resize(40);),這個時候車里面才真正有了40個座椅,這些座椅就可以使用了。
另外這位博友的blog寫的也很清楚,請參考!《c++ vector resize & reserve》
好了,就到這里!