日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

关于vector的resize()的理解

發(fā)布時間:2025/3/21 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于vector的resize()的理解 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

ector的resize(),reserve()把我搞的暈頭轉(zhuǎn)向,老是記不住。現(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元素數(shù)目要小,vector的容量要縮減到resize的第一個參數(shù)大小,既n。并移除那些超出n的元素同時銷毀他們。

如果n比當(dāng)前vector元素數(shù)目要大,在vector的末尾擴(kuò)展需要的元素數(shù)目,如果第二個參數(shù)val指定了,擴(kuò)展的新元素初始化為val的副本,否則按類型默認(rèn)初始化。

注意:如果n大于當(dāng)前的vector的容量(是容量,并非vector的size),將會引起自動內(nèi)存分配。所以現(xiàn)有的pointer,references,iterators將會失效。

?

百度知道找到的一個關(guān)于resize和reserve的生動的例子:點(diǎn)這里

resize(),設(shè)置大小(size);
reserve(),設(shè)置容量(capacity);
size()是分配容器的內(nèi)存大小,而capacity()只是設(shè)置容器容量大小,但并沒有真正分配內(nèi)存。
打個比方:正在建造的一輛公交車,車?yán)锩婵梢栽O(shè)置40個座椅(reserve(40);),這是它的容量,但并不是說它里面就有了40個座椅,只能說明這部車內(nèi)部空間大小可以放得下40張座椅而已。而車?yán)锩姘惭b了40個座椅(resize(40);),這個時候車?yán)锩娌耪嬲辛?0個座椅,這些座椅就可以使用了。


另外這位博友的blog寫的也很清楚,請參考!《c++ vector resize & reserve》


好了,就到這里!
————————————————
原文鏈接:https://blog.csdn.net/ubunfans/article/details/8447833

總結(jié)

以上是生活随笔為你收集整理的关于vector的resize()的理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。