STL:list

文章目录

标准库中的list

  1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器 ,并且该容器可以前后双向迭代
  2. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
  3. listforward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高效。
  4. 与其他的序列式容器相比(arrayvectordeque),list通常在任意位置进行插入、移除元素的执行效率更好。
  5. 与其他序列式容器相比,listforward_list最大的缺陷是不支持任意位置的随机访问 ,比如:要访问list的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间开销;list还需要一些额外的空间 ,以保存每个节点的相关联信息(对于存储类型较小元素的list来说这可能是一个重要的因素)

list的构造

Example:

C++ 复制代码
#include <iostream>
using namespace std;
#include <list>
#include <vector>

// list的构造
void TestList1()
{
    list<int> l1;                         // 构造空的l1
    list<int> l2(4, 100);                 // l2中放4个值为100的元素
    list<int> l3(l2.begin(), l2.end());  // 用l2的[begin(), end())左闭右开的区间构造l3
    list<int> l4(l3);                    // 用l3拷贝构造l4

    // 以数组为迭代器区间构造l5
    int array[] = { 16,2,77,29 };
    list<int> l5(array, array + sizeof(array) / sizeof(int));

    // 列表格式初始化C++11
    list<int> l6{ 1,2,3,4,5 };

    // 用迭代器方式打印l5中的元素
    list<int>::iterator it = l5.begin();
    while (it != l5.end())
    {
        cout << *it << " ";
        ++it;
    }       
    cout << endl;

    // C++11范围for的方式遍历
    for (auto& e : l5)
        cout << e << " ";

    cout << endl;
}

list的迭代器

list的迭代器类型是一个自定义类型,包含了指向结点的指针,重载了*,->,++,``--,==,!=`等运算符。

在使用时可以简单理解为指向结点的指针。

Example:

C++ 复制代码
#include <iostream>
using namespace std;
#include <list>
#include <vector>

// list迭代器的使用
// 注意:遍历链表只能用迭代器和范围for
void PrintList(const list<int>& l)
{
    // 注意这里调用的是list的 begin() const,返回list的const_iterator对象
    for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
    {
        cout << *it << " ";
        // *it = 10; 编译不通过
    }

    cout << endl;
}

void TestList2()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));
    // 使用正向迭代器正向list中的元素
    // list<int>::iterator it = l.begin();   // C++98中语法
    auto it = l.begin();                     // C++11之后推荐写法
    while (it != l.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    // 使用反向迭代器逆向打印list中的元素
    // list<int>::reverse_iterator rit = l.rbegin();
    auto rit = l.rbegin();
    while (rit != l.rend())
    {
        cout << *rit << " ";
        ++rit;
    }
    cout << endl;
}

list的容量

可以看到,相比于stringvectorlist不支持reserveshink_to_fit等接口,因为链表的底层并不是一块连续的空间,每次插入都需要开辟新的空间,所以不必提前开空间,删除同理。不过list支持了resizeclear等接口,使用较少。

list的访问

前文已提到,list不支持随机访问,又因为list是双向循环链表,所以可以获取头部元素和尾部元素。

list的修改

相比于stringvectorlist提供了头插和头删,这也是由于list的底层空间是不连续的有关,元素之间通过指针建立联系,删除头部元素不会导致后续元素的移动,所以list提供了头插和头删,同时还有insert。这些接口在stringvector中要么没有提供,要么不提倡使用,因为效率实在低下。

Example:

C++ 复制代码
#include <iostream>
using namespace std;
#include <list>
#include <vector>

// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{
    int array[] = { 1, 2, 3 };
    list<int> L(array, array + sizeof(array) / sizeof(array[0]));

    // 在list的尾部插入4,头部插入0
    L.push_back(4);
    L.push_front(0);
    PrintList(L);

    // 删除list尾部节点和头部节点
    L.pop_back();
    L.pop_front();
    PrintList(L);
}

// insert /erase 
void TestList4()
{
    int array1[] = { 1, 2, 3 };
    list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));

    // 获取链表中第二个节点
    auto pos = ++L.begin();
    cout << *pos << endl;

    // 在pos前插入值为4的元素
    L.insert(pos, 4);
    PrintList(L);

    // 在pos前插入5个值为5的元素
    L.insert(pos, 5, 5);
    PrintList(L);

    // 在pos前插入[v.begin(), v.end)区间中的元素
    vector<int> v{ 7, 8, 9 };
    L.insert(pos, v.begin(), v.end());
    PrintList(L);

    // 删除pos位置上的元素
    L.erase(pos);
    PrintList(L);

    // 删除list中[begin, end)区间中的元素,即删除list中的所有元素
    L.erase(L.begin(), L.end());
    PrintList(L);
}

// resize/swap/clear
void TestList5()
{
    // 用数组来构造list
    int array1[] = { 1, 2, 3 };
    list<int> l1(array1, array1 + sizeof(array1) / sizeof(array1[0]));
    PrintList(l1);

    // 交换l1和l2中的元素
    list<int> l2;
    l1.swap(l2);
    PrintList(l1);
    PrintList(l2);

    // 将l2中的元素清空
    l2.clear();
    cout << l2.size() << endl;
}

list的迭代器失效

前面说过,大家可将迭代器暂时理解成指针,迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。

C++ 复制代码
// 错误示例
void TestListIterator1()
 {
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array+sizeof(array)/sizeof(array[0]));
 
    auto it = l.begin();
    while (it != l.end())
    {
        // erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
        l.erase(it);  
        ++it;
    }
 }

// 正确示例
void TestListIterator()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array+sizeof(array)/sizeof(array[0]));
    
    auto it = l.begin();
    while (it != l.end())
    {
        l.erase(it++);    // 或 it = l.erase(it);
    }
}

list的反向迭代器

通过前面例子知道,反向迭代器的++就是正向迭代器的--,反向迭代器的--就是正向迭代器的++,因此反向迭 代器的实现可以借助正向迭代器,即:反向迭代器内部可以包含一个正向迭代器,对正向迭代器的接口进行 包装即可。

C++ 复制代码
template<class Iterator>
class ReverseListIterator
{
    // 注意:此处typename的作用是明确告诉编译器,Ref是Iterator类中的类型,而不是静态成员变量
    // 否则编译器编译时就不知道Ref是Iterator中的类型还是静态成员变量
    // 因为静态成员变量也是按照 类名::静态成员变量名 的方式访问的
public:
    typedef typename Iterator::Ref Ref;
    typedef typename Iterator::Ptr Ptr;
    typedef ReverseListIterator<Iterator> Self;
public:
    //
    // 构造
    ReverseListIterator(Iterator it): _it(it){}
    //
    // 具有指针类似行为
    Ref operator*(){
        Iterator temp(_it);--temp;
        return *temp;
    }
    Ptr operator->(){return &(operator*());}
    //
    // 迭代器支持移动
    Self& operator++(){
        --_it;
        return *this;
    }
    Self operator++(int){
        Self temp(*this);--_it;
        return temp;
    }
    Self& operator--(){
        ++_it;
        return *this;
    }
    Self operator--(int)
    {
        Self temp(*this);
        ++_it;
        return temp;
    }
    //
    // 迭代器支持比较
    bool operator!=(const Self& l)const{return _it != l._it;}
    bool operator==(const Self& l)const{return _it == l._it;}
    Iterator _it;
}

list 与 vector的对比

vector list
底层结构 动态顺序表,一段连续空间 带头结点的双向循环链表
随机访问 支持随机访问,访问某个元素效率O(1) 不支持随机访问,访问某个元素效率O(n)
插入和删除 任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(n),插入时有可能需要增容,增容:开辟新空间,拷贝元素,释放就空间,导致效率更低 任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)
空间利用率 底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高 底层结点动态开辟,小姐点容易造成内存碎片,空间利用率低,缓存利用率低
迭代器 原生指针 对原生指针(节点指针)进行封装
迭代器失效 在插入元素时,要给所有的迭代器重新赋值,因为插入元素有可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值,否则会失效 插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使用场景 需要高效存储,支持随机访问,不关心插入删除效率 大量插入和删除操作,不关心随机访问
相关推荐
赵荏苒16 分钟前
Python小白之Pandas1
开发语言·python
丶Darling.18 分钟前
代码随想录 | Day26 | 二叉树:二叉搜索树中的插入操作&&删除二叉搜索树中的节点&&修剪二叉搜索树
开发语言·数据结构·c++·笔记·学习·算法
人生の三重奏25 分钟前
前端——js补充
开发语言·前端·javascript
平凡的小码农1 小时前
JAVA实现大写金额转小写金额
java·开发语言
小飞猪Jay1 小时前
面试速通宝典——10
linux·服务器·c++·面试
yttandb1 小时前
重生到现代之从零开始的C语言生活》—— 内存的存储
c语言·开发语言·生活
我明天再来学Web渗透1 小时前
【hot100-java】【二叉树的层序遍历】
java·开发语言·数据库·sql·算法·排序算法
结衣结衣.1 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
茫茫人海一粒沙1 小时前
Python 代码编写规范
开发语言·python
原野心存1 小时前
java基础进阶知识点汇总(1)
java·开发语言