list

阅读量: 258 编辑

std::list 是 C++ 标准模板库(STL)中的一个容器,它实现了双向链表的数据结构。下面从特点、使用方法、常用操作等方面详细介绍 std::list。

双向链表结构:std::list 由一系列节点组成,每个节点包含数据和指向前一个节点和后一个节点的指针。这使得在链表的任意位置插入和删除元素的时间复杂度为 O(1)。

动态大小:可以在运行时动态地添加和删除元素,无需预先指定大小。

不支持随机访问:不能像数组或 std::vector 那样通过下标直接访问元素,必须通过迭代器顺序访问。

函数用法

  • list<int> l:声明一个 list

  • push_back(e):在链表的尾部插入一个元素。

  • push_front(e):在链表的头部插入一个元素。

  • l.size():返回元素数量

  • pop_back():删除链表的最后一个元素。

  • pop_front():删除链表的第一个元素。

  • sort():对链表中的元素进行排序。

  • reverse():反转链表中的元素顺序。

  • std::find(e):查找元素 e ,std::find(l.begin(), l.end(), 30) == l.end() 表示是否找到元素

  • l.begin():迭代器 list 的开始(地址位置)

  • l.end():迭代器 list 的结束(地址位置)

     // 通过迭代器,循环遍历元素
     for(list<int>::iterator it = l.begin(); it != l.end(); ++it){
         cout << *it << " ";
     }
    
  • l.insert(pos, e):在指定位置插入一个元素。迭代器 pos 与链表的节点绑定。

  • l.erase(pos):删除指定位置或指定范围内的元素。迭代器pos会失效。

  • l.erase(begin, end):将[begin, end)处的元素删除

参考程序

// 爱码岛编程
#include <bits/stdc++.h>
using namespace std;

int main() {
    list<int> l;
    // 插入元素值(节点)
    l.push_back(10);
	l.push_back(20);
	l.push_front(5); // 5 10 20
	l.push_front(15); // 15 5 10 20

    cout << l.size() << endl;

    /*
    l.pop_back();
    l.pop_front();
    l.sort();
    l.reverse();
	*/
    
    // STL 模板的find方法
    list<int>::iterator pos = find(l.begin(), l.end(), 10);
    if (pos != l.end()) {
        cout << "存在10" << endl;
    }

    // 通过迭代器,循环遍历元素 15 5 10 20
    for (list<int>::iterator it = l.begin(); it != l.end(); ++it) {
        cout << *it << " ";
    }

    cout << endl;
	
    // 插入元素,迭代器pos与节点10绑定
    l.insert(pos, 100); // 15 5 100 10 20

    //删除节点10,迭代器pos失效
    l.erase(pos); // 15 5 100 20

    return 0;
}
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司