3.vector容量和大小

2021-04-08  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<vector>

//empty();//判断容器是否为空
//capacity();//容器的容量
//size();//返回容器中元素的个数
//resize(int num);//重新指定容器的长度为num,若容器变长,则以默认值填充新位置,若容器变短,则末尾超出容器的元素被删除
//resize(int num, elem);//重新指定容器的长度为num,若容器变长,则以elem值填充新位置,若容器变短,则末尾超出容器的元素被删除

void printVector(vector<int> v)
{
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << (*it) << " ";
    }
    cout << endl;
}
void test0301()
{
    vector<int> v1;
    for (int i = 0; i < 10; 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;
    }

    v1.resize(15);//如果重新指定比原来长,默认使用0填充新位置
    printVector(v1);

    v1.resize(5);
    printVector(v1);//若容器变短,则末尾超出容器的元素被删除

    v1.resize(15, 100);
    printVector(v1); //容器变长,则以100值填充新位置
}
int main()
{

    test0301();

    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读