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 <iostream>
    #include <vector>
    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;
    } 

结果
在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值