10.list

目录

[1. list的介绍及使用](#1. list的介绍及使用)

[1.1 list的介绍](#1.1 list的介绍)

[1.2 list的使用](#1.2 list的使用)

[1.2.1 list的构造](#1.2.1 list的构造)

[1.2.2 list iterator的使用](#1.2.2 list iterator的使用)

[1.2.3 list capacity](#1.2.3 list capacity)

[1.2.4 list element access](#1.2.4 list element access)

[1.2.5 list modifiers](#1.2.5 list modifiers)

[1.2.6 list的迭代器失效](#1.2.6 list的迭代器失效)

[2. list的模拟实现](#2. list的模拟实现)

[2.1 模拟实现list](#2.1 模拟实现list)

[2.2 list的反向迭代器](#2.2 list的反向迭代器)

[3. list与vector的对比](#3. list与vector的对比)


1. list的介绍及使用

1.1 list的介绍

std::list 是 C++ 标准模板库(STL)中双向链表 实现的线性容器 ------ 你可以把它理解为「一串首尾相连的节点」,每个节点包含数据、指向前一个节点的指针和指向后一个节点的指针。它和 std::vector(数组实现)是 STL 中最常用的线性容器,但设计目标完全不同:list 主打任意位置的高效增删 ,而 vector 主打随机访问

  1. std::list 的核心特性
特性 说明
双向链表结构 每个节点有 prev/next 指针,支持向前 / 向后遍历,无连续内存要求
无随机访问 不能通过索引(如 list[0])直接访问元素,需遍历才能找到目标位置
高效增删 已知位置(迭代器)下,增删元素的时间复杂度为 O(1)(仅修改指针)
动态内存 元素按需分配 / 释放内存,无预分配 / 扩容开销(对比 vector 的扩容拷贝)
不支持容量预留 没有 reserve() 方法,因为链表无需连续内存
迭代器稳定性 增删元素时,除了被操作的节点,其他节点的迭代器 / 指针 / 引用都不会失效

1.2 list的使用

list 中的接口比较多,此处类似,只需要掌握如何正确的使用,然后再去深入研究背后的原理,已达到可扩展的能力。以下为list 中一些 常见的重要接口

1.2.1 list的构造

构造函数(constructor) 接口说明
list (size_type n, const value_type& val = value_type()) 构造的 list 中包含 n 个值为 val 的元素(若未提供 val,则使用类型默认值)
list() 构造空的 list
list (const list& x) 拷贝构造函数,用已有的 list 对象 x 初始化新的 list
list (InputIterator first, InputIterator last) 用迭代器区间 [first, last) 中的元素构造 list(左闭右开,包含 first,不包含 last

代码示例:

#include <iostream>

#include <list>

#include <vector>

int main() {

// 1. 空列表

std::list<int> l1;

// 2. 填充值构造

std::list<int> l2(3, 100);

// 3. 拷贝构造

std::list<int> l3(l2);

// 4. 迭代器区间构造(从vector初始化)

std::vector<int> v = {1,2,3,4};

std::list<int> l4(v.begin(), v.end());

// 打印验证

for (int x : l4) std::cout << x << " "; // 输出: 1 2 3 4

return 0;

}

1.2.2 list iterator的使用

函数声明 接口说明
begin() + end() begin() 返回指向第一个元素 的迭代器;end() 返回指向最后一个元素下一个位置的迭代器(不指向有效元素,作为遍历结束标记)
rbegin() + rend() rbegin() 返回指向最后一个元素 的反向迭代器;rend() 返回指向第一个元素前一个位置的反向迭代器(反向遍历结束标记)


【注意】

  1. begin end 为正向迭代器,对迭代器执行 ++ 操作,迭代器向后移动
  2. rbegin(end) rend(begin) 为反向迭代器,对迭代器执行 ++ 操作,迭代器向前移动

代码示例:

#include <iostream>

#include <list>

using namespace std;

int main() {

// 1. 初始化 list

list<int> myList = {10, 20, 30, 40, 50};

// 2. 正向遍历(使用 begin() + end())

cout << "正向遍历: ";

for (auto it = myList.begin(); it != myList.end(); ++it) {

cout << *it << " "; // 解包迭代器获取元素值,10,20,30,40,50

}

cout << endl;

// 3. 反向遍历(使用 rbegin() + rend())

cout << "反向遍历: ";

for (auto it = myList.rbegin(); it != myList.rend(); ++it) {

cout << *it << " "; // 反向迭代器同样可以解包,50,40,30,20,10

}

cout << endl;

// 4. 利用迭代器修改元素

auto it = myList.begin();

++it; // 移动到第二个元素(20)

*it = 200; // 修改该元素值

cout << "修改后正向遍历: ";

for (int num : myList) { // 范围for循环底层也是迭代器

cout << num << " ";

}

cout << endl;

return 0;

}

1.2.3 list capacity

函数声明 接口说明
empty() 检测 list 是否为空,是返回 true,否则返回 false
size() 返回 list 中有效节点的个数

代码示例:

#include <iostream>

#include <list>

using namespace std;

int main() {

list<int> l;

// 初始状态:空列表

cout << "是否为空: " << (l.empty() ? "是" : "否") << endl;

cout << "元素个数: " << l.size() << endl;

// 添加元素

l.push_back(1);

l.push_back(2);

l.push_back(3);

cout << "添加元素后是否为空: " << (l.empty() ? "是" : "否") << endl;

cout << "添加元素后元素个数: " << l.size() << endl;

// 删除一个元素

l.pop_back();

cout << "删除后元素个数: " << l.size() << endl;

// 清空列表

l.clear();

cout << "清空后是否为空: " << (l.empty() ? "是" : "否") << endl;

cout << "清空后元素个数: " << l.size() << endl;

return 0;

}

1.2.4 list element access

函数声明 接口说明
front() 返回 list 的第一个节点中值的引用
back() 返回 list 的最后一个节点中值的引用

代码示例:

#include <iostream>

#include <list>

using namespace std;

int main() {

list<int> l = {10, 20, 30, 40, 50};

// 访问首尾元素

cout << "第一个元素: " << l.front() << endl;//10

cout << "最后一个元素: " << l.back() << endl;//50

// 修改首尾元素(因为返回的是引用)

l.front() = 100;

l.back() = 500;

cout << "修改后第一个元素: " << l.front() << endl;//100

cout << "修改后最后一个元素: " << l.back() << endl;//500

// 遍历验证

cout << "遍历所有元素: ";

for (int num : l) {

cout << num << " ";//100 20 30 40 500

}

cout << endl;

return 0;

}

1.2.5 list modifiers

函数声明 接口说明
push_front list 首元素前插入值为 val 的元素
pop_front 删除 list 中第一个元素
push_back list 尾部插入值为 val 的元素
pop_back 删除 list 中最后一个元素
insert list position 位置插入值为 val 的元素
erase 删除 list position 位置的元素
swap 交换两个 list 中的元素
clear 清空 list 中的有效元素

代码示例:

#include <iostream>
#include <list>
using namespace std;

// 辅助函数:打印 list
void printList(const list<int>& l, const string& desc) {
cout << desc << ": ";
for (int num : l) {
cout << num << " ";
}
cout << endl;
}

int main() {
list<int> l1;

// 1. 首尾插入
l1.push_back(10); // 尾部插入 10
l1.push_front(20); // 头部插入 20
printList(l1, "push_back/push_front 后");//push_back/push_front 后: 20 10

// 2. 首尾删除
l1.pop_back(); // 删除尾部
l1.pop_front(); // 删除头部
printList(l1, "pop_back/pop_front 后");

// 3. 重新填充数据
l1.push_back(30);
l1.push_back(40);
l1.push_back(50);
printList(l1, "重新填充后");//重新填充后: 30 40 50

// 4. insert 插入(在第二个位置插入 35)
auto it = l1.begin();
++it; // 移动到第二个元素(40)之前
l1.insert(it, 35);
printList(l1, "insert 插入 35 后");//insert 插入 35 后: 30 35 40 50

// 5. erase 删除(删除刚才插入的 35)
--it; // 回到 35 的位置
l1.erase(it);
printList(l1, "erase 删除 35 后");//erase 删除 35 后: 30 40 50

// 6. swap 交换两个 list
list<int> l2 = {100, 200, 300};
l1.swap(l2);
printList(l1, "swap 后 l1");//swap 后 l1: 100 200 300
printList(l2, "swap 后 l2");//swap 后 l2: 30 40 50

// 7. clear 清空
l1.clear();
printList(l1, "clear 后 l1");

return 0;
}

1.2.6 list的迭代器失效

前面说过,此处大家可将迭代器暂时理解成类似于指针, 迭代器失效即迭代器所指向的节点的无 效,即该节点被删除了 。因为 list 的底层结构为带头结点的双向循环链表 ,因此 list 中进行插入 时是不会导致 list 的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭 代器,其他迭代器不会受到影响
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);
}
}
写法 1(l.erase(it++) :后置 ++ 的特性是「先返回 it 的旧值(传给 erase),再将 it 移动到下一个节点」。此时 erase 销毁的是旧值指向的节点,而 it 已经提前移动到了下一个有效节点,避免失效。

写法 2(it = l.erase(it)list::erase 的返回值是「被删除节点的下一个有效迭代器」,直接用这个返回值更新 it,逻辑更清晰,是工业界推荐写法。

2. list的模拟实现

2.1 模拟实现list

#pragma once
#include<assert.h>

//惯例
//如果一个类全部公有用struct
namespace bit
{
template<class T>
struct list_node
{
T _data;
list_node<T>* _next;
list_node<T>* _prev;

list_node(const T& x = T())
:_data(x)
, _next(nullptr)
, _prev(nullptr)
{}
};

//typedef list_iterator<T, T&, T*> iterator;
//typedef list_iterator<T, const T&, const T*> const_iterator;

//T:迭代器指向的节点数据类型(比如 int/string/ 自定义类型);

//Ref:解引用(operator*())返回值的类型(T&const T&,控制是否可修改数据);

//Ptr:箭头访问(operator->())返回值的类型(T*const T*,控制指针访问权限);
template<class T,class Ref,class Ptr>
struct list_iterator
{
typedef list_node<T> Node;//链表节点类型起别名 Node
typedef list_iterator<T,Ref,Ptr> Self;//迭代器类型 list_iterator<T, Ref, Ptr> 起别名 Self
Node* _node;

list_iterator(Node* node)
:_node(node)
{}

//解引用(获取节点数据)
Ref operator*()
{
return _node->_data;
}

//箭头访问(针对自定义类型)

Ptr operator->()
{
return &_node->_data;
}

//前置,迭代器后移(指向后继节点)
Self& operator++()
{
_node = _node->_next;
return *this;
}

//迭代器前移(指向前驱节点)
Self& operator--()
{
_node = _node->_prev;
return *this;
}

//后置,迭代器后移(先返回旧值)
Self operator++(int)
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}

//迭代器前移(先返回旧值)
Self operator--(int)
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}

bool operator!=(const Self& s)
{
return _node != s._node;
}

bool operator==(const Self& s)
{
return _node == s._node;
}
};

template<class T>
class list
{
typedef list_node<T> Node;
public:
/*typedef list_iterator<T> iterator;
typedef list_const_iterator<T> const_iterator;*/

typedef list_iterator<T, T&, T*> iterator;//可写迭代器
typedef list_iterator<T, const T&, const T*> const_iterator;//只读迭代器

iterator begin()
{
return iterator(_head->_next);
}

iterator end()
{
return iterator(_head);
}

const_iterator begin() const
{
return const_iterator(_head->_next);
}

const_iterator end() const
{
return const_iterator(_head);
}

void empty_init()
{
_head = new Node();
_head->_next = _head;
_head->_prev = _head;
_size = 0;
}

list()
{
empty_init();
}

//lt2(lt1),拷贝构造
list(const list<T>& lt)
{
empty_init();
for (auto& e : lt)
{
push_back(e);
}
}

//lt2=lt3,赋值重载
list<T>& operator=(list<T> lt)
{
swap(lt);
return *this;
}

~list()
{
clear();
delete _head;
_head = nullptr;
}

void swap(list<T>& tmp)
{
std::swap(_head, tmp._head);
std::swap(_size, tmp._size);
}

void clear()
{
auto it = begin();
while (it != end())
{
it = erase(it);
}
}

//填充值构造函数

list(size_t n,const T& val = T())
{
empty_init();
for (size_t i = 0; i < n; i++)
{
push_back(val);
}
}

void push_back(const T& x)
{
/*Node* new_node = new Node(x);
Node* tail = _head->_prev;

tail->_next = new_node;
new_node->_prev = tail;

new_node->_next = _head;
_head->_prev = new_node;*/
insert(end(), x);
}

void push_front(const T& x)
{
insert(begin(), x);
}

void pop_back()
{
erase(begin());
}

void pop_front()
{
erase(--end());
}

iterator insert(iterator pos, const T& val)
{
Node* cur = pos._node;
Node* newnode = new Node(val);
Node* prev = cur->_prev;

prev->_next = newnode;
newnode->_prev = prev;

newnode->_next = cur;
cur->_prev = newnode;
++_size;

return iterator(newnode);
}

iterator erase(iterator pos)
{
assert(pos != end());

Node* del = pos._node;
Node* prev = del->_prev;
Node* next = del->_next;

prev->_next = next;
next->_prev = prev;
delete del;
--_size;

return iterator(next);
}

private:
Node* _head;
size_t _size;
};

//通用模板版本
template <class T>
void swap(T& a, T& b)
{
T c(a); a = b; b = c;
}

//list 特化版本

template <class T>
void swap(list<T>& a, list<T>& b)
{
a.swap(b);
}
}

2.2 list的反向迭代器

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

3. list与vector的对比

vector 与 list 都是 STL 中非常重要的序列式容器,由于两个容器的底层结构不同,导致其特性以及应用场景不同,其主要不同如下:

维度 vector list
底层结构 动态顺序表,一段连续空间 带头结点的双向循环链表
随机访问 支持随机访问,访问某个元素效率 O(1) 不支持随机访问,访问某个元素效率 O(N)
插入和删除 任意位置插入和删除效率低,需要搬移元素,时间复杂度为 O(N);插入时有可能需要扩容,开辟新空间、拷贝元素、释放旧空间,导致效率更低 任意位置插入和删除效率高,不需要搬移元素,时间复杂度为 O(1)
空间利用率 底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高 底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低
迭代器 原生态指针 对原生态指针(节点指针)进行封装
迭代器失效 插入元素时,可能导致重新扩容,使原来迭代器失效;删除时,当前迭代器需要重新赋值否则会失效 插入元素不会导致迭代器失效;删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使用场景 需要高效存储,支持随机访问,不关心插入删除效率 大量插入和删除操作,不关心随机访问

✨ 一句话记忆口诀

  • vector:连续存、随机读、增删慢、迭代器脆
  • list:分散存、遍历读、增删快、迭代器稳
相关推荐
tankeven2 小时前
HJ139 小红的01子序列计数(hard)
c++·算法
weixin_649555672 小时前
C语言程序设计第四版(何钦铭、颜晖)第十章函数与程序设计之汉诺塔问题
c语言·c++·算法
xushichao19892 小时前
实时数据压缩库
开发语言·c++·算法
minji...2 小时前
Linux 文件系统 (三) 软连接和硬链接
linux·运维·服务器·c++·算法
liuyao_xianhui3 小时前
优选算法_模拟_提莫攻击_C++
开发语言·c++·算法·动态规划·哈希算法·散列表
.select.3 小时前
c++ 移动赋值/移动构造函数
开发语言·c++
散峰而望3 小时前
【基础算法】从入门到实战:递归型枚举与回溯剪枝,暴力搜索的初级优化指南
数据结构·c++·后端·算法·机器学习·github·剪枝
setmoon2143 小时前
C++代码规范化工具
开发语言·c++·算法
汉克老师4 小时前
GESP2026年3月认证C++三级( 第一部分选择题(9-15))
c++·字符串·数组长度·反码·枚举算法·gesp三级·gesp3级