关于vector的resize()的理解
ector的resize(),reserve()把我搞的暈頭轉(zhuǎn)向,老是記不住?,F(xiàn)在把自己的一點(diǎn)理解記錄在這里。
先看看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中元素的數(shù)目。
如果n比當(dāng)前的vector元素?cái)?shù)目要小,vector的容量要縮減到resize的第一個(gè)參數(shù)大小,既n。并移除那些超出n的元素同時(shí)銷毀他們。
如果n比當(dāng)前vector元素?cái)?shù)目要大,在vector的末尾擴(kuò)展需要的元素?cái)?shù)目,如果第二個(gè)參數(shù)val指定了,擴(kuò)展的新元素初始化為val的副本,否則按類型默認(rèn)初始化。
注意:如果n大于當(dāng)前的vector的容量(是容量,并非vector的size),將會(huì)引起自動(dòng)內(nèi)存分配。所以現(xiàn)有的pointer,references,iterators將會(huì)失效。
?
百度知道找到的一個(gè)關(guān)于resize和reserve的生動(dòng)的例子:點(diǎn)這里
resize(),設(shè)置大小(size);
reserve(),設(shè)置容量(capacity);
size()是分配容器的內(nèi)存大小,而capacity()只是設(shè)置容器容量大小,但并沒有真正分配內(nèi)存。
打個(gè)比方:正在建造的一輛公交車,車?yán)锩婵梢栽O(shè)置40個(gè)座椅(reserve(40);),這是它的容量,但并不是說它里面就有了40個(gè)座椅,只能說明這部車內(nèi)部空間大小可以放得下40張座椅而已。而車?yán)锩姘惭b了40個(gè)座椅(resize(40);),這個(gè)時(shí)候車?yán)锩娌耪嬲辛?0個(gè)座椅,這些座椅就可以使用了。
另外這位博友的blog寫的也很清楚,請(qǐng)參考!《c++ vector resize & reserve》
好了,就到這里!
————————————————
原文鏈接:https://blog.csdn.net/ubunfans/article/details/8447833
總結(jié)
以上是生活随笔為你收集整理的关于vector的resize()的理解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python求解线性方程组
- 下一篇: Python里面数组拼接方法介绍