vector的resize和reserve

官方文档

resize:http://www.cplusplus.com/reference/vector/vector/resize/
reserve:http://www.cplusplus.com/reference/vector/vector/reserve/

resize

Resizes the container so that it contains n elements.
1、If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
如果n比当前容器size小,当前容器内容会被缩减到前n个,多余的被清除。
2、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.
如果n比当前容器的size大,容器size或被扩充到n,如果这扩充的n个数指定了数值,则填入指定数值,否则,为默认值。
3、If n is also greater than the current container capacity, an automatic
reallocation of the allocated storage space takes place.
如果n比当前容器的容积都大,内容空间会被重新分配。
Notice that this function changes the actual content of the container
by inserting or erasing elements from it.
注意这个函数会影响容器的size。

reserve

Request a change in capacity Requests that the vector capacity be at
least enough to contain n elements.

1、If n is greater than the current vector capacity, the function causes
the container to reallocate its storage increasing its capacity to n
(or greater).
如果n大于当前容器容积,容器会重新分配内存。
2、In all other cases, the function call does not cause a reallocation
and the vector capacity is not affected.
其他情况,不产生影响
Note:This function has no effect on the vector size and cannot alter its
elements.
这个函数对size 没有影响,也不会改变元素值。

size和capacity辨析

类比:

    int a[10],index=5;
    for(int i=0;i<index;i++) cin>>a[i]

10是我们开辟的空间大小,5是我们实际使用的空间,此空间的单位是元素个数,而非字节。
那么对应的capacity对应开辟空间,size对应使用空间。

测试代码

    #include 
    #include 
    using namespace std;
    
    int main(){
    	vector<int> a;
    	a.reserve(100);
    	cout<<a.size()<<"  "<<a.capacity()<<endl;
    	a.resize(150);
    	cout<<a.size()<<"  "<<a.capacity()<<endl;
    	a.reserve(50);
    	cout<<a.size()<<"  "<<a.capacity()<<endl;
    	a.resize(50);
    	cout<<a.size()<<"  "<<a.capacity()<<endl;
    } 

结果
vector的resize和reserve_第1张图片

你可能感兴趣的:(C++)