vector容器成员函数resize与reserve的区别

本文详细解释了C++中向量的resize与reserve方法的区别。resize用于设置向量的大小,使其大小等于指定值;reserve则用于设置向量的容量,但不改变其大小。文章通过示例展示了这两种操作如何影响向量的大小、容量及最大大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

resize是设置向量的大小:即向量的大小与容量相同。而reserve是设置向量的容量,并不改变向量的大小。另外:向量的最大大小是固定住,不可改变。例子:

#include "stdafx.h"

#include <iostream>

#include <vector>

 

using namespace std;

 

typedefvector<int> VEC_INT;

int_tmain(int argc, _TCHAR* argv[])

{

    VEC_INTthevec;

    cout<<"before insert data:"<<endl;

    cout<<"the size of vector:"<<thevec.size()<<endl;

    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;

    cout<<"the max size of vector:"<<thevec.max_size()<<endl;

    cout<<"after insert data:"<<endl;

    thevec.push_back(42);

    cout<<"the size of vector:"<<thevec.size()<<endl;

    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;

    cout<<"the max size of vector:"<<thevec.max_size()<<endl;

 

    thevec.reserve(100);

    cout<<"After reserve (100):"<<endl;

    cout<<"the size of vector:"<<thevec.size()<<endl;

    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;

    cout<<"the max size of vector:"<<thevec.max_size()<<endl;

 

    thevec.resize(1000);

    cout<<"After resize (1000):"<<endl;

    cout<<"the size of vector:"<<thevec.size()<<endl;

    cout<<"the capasity of vector:"<<thevec.capacity()<<endl;

    cout<<"the max size of vector:"<<thevec.max_size()<<endl;

    return 0;

}

运行结果:

可以看出:默认情况下,向量的大小和容量是相同的,如果用resize改变向量的大小,则同时改变了向量的容量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值