【C++学习纪录】vector容器——容量与大小

C++容器操作详解
本文详细介绍了C++中容器的几种关键操作,包括empty()用于判断容器是否为空,capacity()和size()分别用于获取容器的容量和元素数量,以及resize()如何改变容器的长度并填充新位置或删除超出长度的元素。

1、empty() 判断容器是否为空。为空返回真,不为空返回假。
2、capacity() 返回容器的容量
3、size() 返回容器中元素的个数。元素个数不一定等于容器容量。
4、resize(int num) 重新指定容器的长度为num。若容器变长,以默认值0填充新位置。如果容器变短,则末尾超出容器长度的元素被删除。
5、resize(int num, elem) 重新指定容器的长度为num。若容器变长,以elem值填充新位置。如果容器变短,则末尾超出容器长度的元素被删除。

一、empty() 判断容器是否为空。为空返回真,不为空返回假。

#include<iostream>
using namespace std;
#include<vector>

int main()
{
    vector<int> v;
    if(v.empty())
    {
        cout << "Vector is empty" << endl;
    }
    else
    {
        cout << "Vector isn't empty" << endl;
    }
    
    system("pause");
}

运行结果:

Vector is empty
请按任意键继续. . .

二、capacity()和size()

#include<iostream>
using namespace std;
#include<vector>

int main()
{
    vector<int> v;
    for (int i = 1; i <= 5; i++)
    {
        v.push_back(i);
    }
    cout << "The capacity of vector is " << v.capacity() << endl;
    cout << "The size of vector is " << v.size() << endl;
    system("pause");
}

运行结果:

The capacity of vector is 8
The size of vector is 5
请按任意键继续. . .

会发现,尾插法存入数据时,容器的capacity会大于size。

三、**resize()**重新指定容器的长度为num

#include<iostream>
using namespace std;
#include<vector>

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

int main()
{
    //用尾插法存入5个数
    vector<int> v;
    for (int i = 1; i <= 5; i++)
    {
        v.push_back(i);
    }
    cout << "The capacity of vector is " << v.capacity() << endl;
    cout << "The size of vector is " << v.size() << endl;
    printVector(v);
    cout << endl;

    //重新指定大小,该大小大于原容器容量,新位置用10填充
    v.resize(10, 100);
    cout << "The capacity of vector is " << v.capacity() << endl;
    cout << "The size of vector is " << v.size() << endl;
    printVector(v);
    cout << endl;
    
    //重新指定大小,该大小小于原容量大小
    v.resize(2);
    cout << "The capacity of vector is " << v.capacity() << endl;
    cout << "The size of vector is " << v.size() << endl;
    printVector(v);
    system("pause");
}

运行结果:

The capacity of vector is 8
The size of vector is 5
1 2 3 4 5

The capacity of vector is 10
The size of vector is 10
1 2 3 4 5 100 100 100 100 100

The capacity of vector is 10
The size of vector is 2
1 2
请按任意键继续. . .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值