C++,STL 038(24.10.20)

时间:2024-10-27 07:37:37

内容

对list容器(链表)的大小进行操作。

运行代码

#include <iostream>
#include <list>

using namespace std;

void printList(const list<int> &l)
{
    for (list<int>::const_iterator it = l.begin(); it != l.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}

void test01()
{
    list<int> l1;
    for (int i = 0; i < 10; i++)
    {
        l1.push_back(i);
    }
    printList(l1);

    if (l1.empty()) // here,容器为空则返回true,反之则返回false
    {
        cout << "容器为空" << endl;
    }
    else
    {
        cout << "容器不为空" << endl;
    }

    cout << "容器大小:" << l1.size() << endl; // here

    l1.resize(12); // here,容器变长且用默认值0来填充容器新位置
    printList(l1);

    l1.resize(15, 1); // here,容器变长且用指定元素来填充新位置
    printList(l1);

    l1.resize(5); // here,容器变短且将容器中超出尾部长度的元素删除
    printList(l1);
}

int main()
{
    test01();

    return 0;
}

输出结果