list学习之创建,初始化assign,赋值操作operator=, empty,size,max_size

list 是支持常数时间从容器任何位置插入和移除元素的容器。不支持快速随机访问。它通常实现为双向链表。与 forward_list 相比,此容器提供双向迭代但在空间上效率稍低。下面我们先来学习list的创建,初始化assign,赋值操作operator=, empty,size,max_size

代码实现:

#include <list>
#include <iostream>

using namespace std;

void createListInit()
{
    //1.创建空forword_list
    list<int> list1;
    cout << "list1.isEmpty = " << list1.empty() << " list1.size = " << list1.size() << " list1.max_size = " << list1.max_size() << endl;

    //2.创建list2有2个元素,值为随机值
    list<int> list2(2);
    cout << "list2.isEmpty = " << list2.empty() << " list2.size = " << list2.size() << " list2.max_size = " << list2.max_size()<< endl;
    cout << "list2的值为:" << endl;
    for(auto &val: list2)
    {
        cout << val << "\t";
    }
    cout << endl;

    //3.创建list3有3个元素,分别为21, 22, 23
    list<int> list3 = {21, 22, 23};
    cout << "list3.isEmpty = " << list3.empty()<< " list3.size = " << list3.size() << " list3.max_size = " << list3.max_size() << endl;
    cout << "list3的值为:" << endl;
    for(auto &val: list3)
    {
        cout << val << "\t";
    }
    cout << endl;

    //4.创建list4,用list3赋值
    list<int> list4 = list3;
    //list<int> list4(list3);//这两种方法都可以
    cout << "list4.isEmpty = " << list4.empty()<< " list4.size = " << list4.size() << " list4.max_size = " << list4.max_size() << endl;
    cout << "list4的值为:" << endl;
    for(auto &val: list4)
    {
        cout << val << "\t";
    }
    cout << endl;

    //5.创建list5用assign进行赋值
    list<int> list5;
    list5.assign({24, 25, 26, 27});
    cout << "list5的值为:" << endl;
    for(auto &val: list5)
    {
        cout << val << "\t";
    }
    cout << endl;
    //6.创建list6用list4进行初始化
    list<int> list6(list4.begin(), list4.end());
    cout << "list6的值为:" << endl;
    for(auto &val: list6)
    {
        cout << val << "\t";
    }
    cout << endl;
    //7.创建list7用assign设定容器大小和初始值
    list<int> list7;
    list7.assign(5, 18);//list7有5个元素,每个元素为18
    cout << "list7的值为:" << endl;
    for(auto &val: list7)
    {
        cout << val << "\t";
    }
    cout << endl;
}

int main()
{
    createListInit();
    cout << endl;

    cout << " Hello World!" << endl;
    return 0;
}

运行结果

《list学习之创建,初始化assign,赋值操作operator=, empty,size,max_size》

参考:

https://zh.cppreference.com/w/cpp/container/list

http://www.cplusplus.com/reference/list/list/

 

    原文作者:江湖故人2008
    原文地址: https://blog.csdn.net/chenyijun/article/details/115093415
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞