vector容器的容量与大小

该段代码展示了C++中vector容器的使用,包括初始化、打印元素、检查empty状态、获取capacity和size,以及resize函数改变大小。当resize扩大容器时,新位置默认填充0;缩小容器时,超出部分元素被删除。随着向vector添加元素,其容量会比大小大,以防止频繁扩容,差距随大小增加而增大。
摘要由CSDN通过智能技术生成

源代码如下:

#include<iostream>
#include <vector>
using namespace std;
#include <string>
void printVector(vector<int>& v) {

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << " ";
    }
    cout << endl;
}

void test01()
{
    vector<int> v1;
    for (int i = 0; i <212; i++)
    {
        v1.push_back(i);
    }
    printVector(v1);
    if (v1.empty())
    {
        cout << "v1为空" << endl;
    }
    else
    {
        cout << "v1不为空" << endl;
        cout << "v1的容量 = " << v1.capacity() << endl;
        cout << "v1的大小 = " << v1.size() << endl;
    }

    //resize 重新指定大小 ,若指定的更大,默认用0填充新位置,可以利用重载版本替换默认填充
    v1.resize(15, 10);
    printVector(v1);

    //resize 重新指定大小 ,若指定的更小,超出部分元素被删除
    v1.resize(5);
    printVector(v1);
}

int main() {

    test01();

    system("pause");

    return 0;
}

为什么这个容器的容量和大小不一样,并随着大小的增加容量与大小的差距越来越大

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值