list基本用法

来源:互联网 发布:广通软件怎么样 编辑:程序博客网 时间:2024/06/03 21:39

List容器在我们代码开发中的使用非常频繁

注:下面list蓝色介绍来自于度娘

listC++标准模版库(STL,StandardTemplate Library)中的部分内容。实际上,list容器就是一个双向链表,可以高效地进行插入删除元素。

a.使用list容器之前必须加上<vector>头文件:#include<list>;

b.list属于std命名域的内容,因此需要通过命名限定:usingstd::list;也可以直接使用全局的命名空间方式:usingnamespace std;

1.创建list

/*建一个含三个默认值是0的元素的链表*/

 list<int>a0;

/*建一个含4个元素的链表,值都是3*/

list<int>a(4,3);

/*给每个元素单独给值*/

list<int> a { 2,6, 7, 8, 9};

3.list的查询

a.使用list<int>a1(4,3)方法来初始化

#include"iostream"

#include"list"

usingnamespace std;

intmain()

{

     list<int>a1(4,3);

   list<int>::iterator it;

   for(it=a1.begin();it!=a1.end();it++)

   {

       cout<<"*it:"<<*it<<endl;

   }

   cout<<endl;

}

运行结果:

*it:3

*it:3

*it:3

*it:3

b.使用list<int>a1{56,7,8,9};进行初始化list


#include"iostream"

#include"list"

usingnamespace std;

intmain()

{

     list<int>a1{5,6,7,8,9};

     //list<int>a1(5,3);

    list<int>::iterator it;

    for(it=a1.begin();it!=a1.end();it++)

    {

           cout<<"*it:"<<*it<<endl;

    }

    cout<<endl;

}

注:这个时候编译提示,’a’mustbe initialized by constructor, not by '{…}'nomatching function for call to‘std::__cxx11::list<int>::list(<brace-enclosed initializerlist>)’,编译的时候加上-std=c++11ok,例如:


g++test.cpp -std=c++11 -o out


运行结果如下:

*it:5

*it:6

*it:7

*it:8

*it:9

 

原创粉丝点击