摘要:std::list 底层是带头双向循环链表,和 vector 连续数组的特性差异巨大。vector 迭代器本质是原生指针,而 list 节点散落在堆上,必须自己封装迭代器。本文从零手写简易版 bit::list,讲解节点结构、迭代器复用方案、增删接口、拷贝赋值、迭代器失效、list.sort 的性能坑点,同时对比 vector,理清 STL 容器与迭代器的设计思想,也是面试高频考点。 关键词:C++、STL、list、双向循环链表、迭代器、迭代器失效
目录
[1. 前言](#1. 前言)
[2. list 底层结构:带头双向循环链表](#2. list 底层结构:带头双向循环链表)
[3. list 迭代器的设计(重难点)](#3. list 迭代器的设计(重难点))
[4. list 核心接口实现](#4. list 核心接口实现)
[5. list 的 sort 性能问题(实验对比)](#5. list 的 sort 性能问题(实验对比))
[6. 迭代器失效总结(面试重点)](#6. 迭代器失效总结(面试重点))
[7. 范围 for 底层原理](#7. 范围 for 底层原理)
[8. const 迭代器的意义](#8. const 迭代器的意义)
[9. list 适用场景](#9. list 适用场景)
[10. 代码缺陷与拓展方向](#10. 代码缺陷与拓展方向)
[11. 完整源码](#11. 完整源码)
1. 前言
std::list 是 STL 中典型的链表容器,底层为带头双向循环链表 。 vector 是连续的动态数组,支持随机访问,但头部、中间插入删除需要挪动数据,效率低; list 的每个节点独立在堆上开辟空间,任意位置插入删除 O (1),代价是不支持随机访问,内存分散,缓存命中率差。
vector 的迭代器可以直接用原生指针充当;但是 list 节点地址不连续,原生指针无法满足统一迭代行为,所以需要封装迭代器类,这也是本节课最核心、最难理解的地方。
本文手写实现一个简易版 bit::list,覆盖节点、迭代器、增删改查、各种构造、拷贝赋值、swap、clear 等接口,同时附带测试代码与性能对比代码。
2. list 底层结构:带头双向循环链表
2.1 节点结构体 list_node
template<class T>
struct list_node
{
list_node<T>* _next;
list_node<T>* _prev;
T _data;
list_node(const T& x = T())
:_next(nullptr)
,_prev(nullptr)
,_data(x)
{}
};
每个节点包含三部分:前驱指针 _prev、后继指针 _next、数据 _data。
2.2 带头 + 循环的优势
_head哨兵头结点,不存储有效数据;- 空链表:
_head->_next = _head,_head->_prev = _head,自环; - 好处:头尾插入删除不需要单独判空,统一逻辑,简化代码。
✅ 优点:任意位置插入删除仅修改指针,O (1) ❌ 缺点:内存不连续,CPU 缓存命中率低,遍历慢;不支持随机访问,不能 it + n
3. list 迭代器的设计(重难点)
vector 迭代器 = 原生指针;list 迭代器 = 对节点指针的封装。
如果分开写普通迭代器和 const 迭代器,会出现大量重复代码。这里采用模板参数 Ref 实现复用同一个迭代器模板:
template<class T, class Ref>
struct list_iterator
{
using Self = list_iterator<T, Ref>;
using Node = list_node<T>;
Node* _node;
list_iterator(Node* node)
:_node(node)
{}
Ref operator*()
{
return _node->_data;
}
// 前置++
Self& operator++()
{
_node = _node->_next;
return *this;
}
// 后置++
Self operator++(int)
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}
// 前置--
Self& operator--()
{
_node = _node->_prev;
return *this;
}
// 后置--
Self operator--(int)
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
bool operator==(const Self& s) const
{
return _node == s._node;
}
};
在 list 类内部重定义:
using iterator = list_iterator<T, T&>;
using const_iterator = list_iterator<T, const T&>;
iterator:解引用返回T&,可读可写const_iterator:解引用返回const T&,只读,禁止修改元素
list 迭代器属于 双向迭代器 Bidirectional Iterator ,仅支持 ++ /--,不支持随机访问,所以
std::sort不能直接接收 list 迭代器!
begin () 和 end ()
iterator begin()
{
return iterator(_head->_next);
}
iterator end()
{
return iterator(_head);
}
- begin:指向第一个有效节点
- end:指向哨兵头结点,end 是合法迭代器,禁止解引用
const 版本 begin/end,给 const 对象使用,返回 const_iterator。
4. list 核心接口实现
4.1 empty_init 初始化函数
所有构造函数复用这个函数,创建哨兵节点,形成自环:
void empty_init()
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
}
4.2 insert 插入(核心接口)
push_back、push_front 全部复用 insert,减少冗余代码
void insert(iterator pos, const T& x)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* newnode = new Node(x);
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
++_size;
}
✅ 重要特性:insert 不会导致任何迭代器失效,只是新增节点,原有节点地址不变。
void push_back(const T& x)
{
insert(end(), x);
}
void push_front(const T& x)
{
insert(begin(), x);
}
4.3 erase 删除接口
iterator erase(iterator pos)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;
prev->_next = next;
next->_prev = prev;
delete cur;
--_size;
return iterator(next);
}
erase 返回下一个有效迭代器,所以使用方式为 it = erase(it),防止野指针。 pop_back、pop_front 复用 erase:
void pop_back()
{
erase(--end());
}
void pop_front()
{
erase(begin());
}
4.4 构造、拷贝、赋值、swap
支持:无参构造、n 个 val 构造、迭代器区间构造、initializer_list 初始化(C++11)
// 拷贝构造
list(const list<T>& lt)
{
empty_init();
for (auto& e: lt)
{
push_back(e);
}
}
// 赋值重载
list<T>& operator=(const list<T>& lt)
{
if (this != <)
{
clear();
for (auto& e : lt)
{
push_back(e);
}
}
return *this;
}
void swap(list<T>& lt)
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}
swap 只是交换指针和 size,O (1),非常高效。
4.5 clear 与析构
void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}
~list()
{
clear();
delete _head;
_head = nullptr;
_size = 0;
}
5. list 的 sort 性能问题(实验对比)
std::sort底层是快排,要求随机访问迭代器 ,list 只有双向迭代器,不能直接用全局 sort。 所以 list 提供成员函数 lt.sort(),底层是归并排序。
我们做两组对比:
- 直接调用
lt.sort()(归并排序) - list 拷贝到 vector → vector 用 std::sort 排序 → 再拷回 list
实验结论:大数据场景下,vector+std::sort 通常比 list 自带 sort 更快! 原因:vector 连续内存,CPU 缓存友好;list 节点分散,大量缺页缓存失效,拖慢速度。
测试代码:
void test_op2()
{
srand(time(0));
const int N = 1000000;
list<int> lt1;
list<int> lt2;
for (int i = 0; i < N; ++i)
{
auto e = rand() + i;
lt1.push_back(e);
lt2.push_back(e);
}
int begin1 = clock();
vector<int> v(lt2.begin(), lt2.end());
sort(v.begin(), v.end());
lt2.assign(v.begin(), v.end());
int end1 = clock();
int begin2 = clock();
lt1.sort();
int end2 = clock();
printf("list copy vector sort copy list sort:%d\n", end1 - begin1);
printf("list sort:%d\n", end2 - begin2);
}
6. 迭代器失效总结(面试重点)
- list
- insert:全部迭代器不失效
- erase:仅被删除位置的迭代器失效,其余迭代器有效
- vector
- insert:扩容时全部迭代器失效;不扩容,插入位置之后迭代器失效
- erase:删除位置之后所有迭代器失效
核心原因:vector 是连续数组,插入删除会挪动元素;list 节点独立,只修改指针,其他节点地址不变。
7. 范围 for 底层原理
for (auto e : lt)
{
cout << e << " ";
}
范围 for 是语法糖,编译器自动翻译成迭代器遍历版本:
auto it = lt.begin();
while(it != lt.end())
{
*it;
++it;
}
只要我们正确实现 begin、end、迭代器 ++、!=,范围 for 就能直接使用。
8. const 迭代器的意义
当容器作为 const 引用传入函数时,只能调用 const 成员 begin () const、end () const,返回 const_iterator,解引用为 const 引用,禁止修改容器内数据,保证常量容器只读。
void Print(const bit::list<int>& lt)
{
bit::list<int>::const_iterator it = lt.begin();
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
9. list 适用场景
✅ 适合:频繁在任意位置插入、删除,遍历、排序很少,不需要随机访问 ❌ 不适合:大量遍历查找、排序、随机访问,优先选择 vector
10. 代码缺陷与拓展方向
- 缺少反向迭代器 rbegin /rend
- 没有实现 list 独有接口 splice、remove、unique、reverse(splice 是 list 王牌接口,转移节点 O (1),不拷贝数据)
- 拷贝赋值现代写法(swap 版)可以进一步优化,异常更安全
- 没有实现移动构造、移动赋值
11. 完整源码
List.h
#pragma once
namespace bit
{
template<class T>
struct list_node
{
list_node<T>* _next;
list_node<T>* _prev;
T _data;
list_node(const T& x = T())
:_next(nullptr)
,_prev(nullptr)
,_data(x)
{}
};
template<class T, class Ref>
struct list_iterator
{
using Self = list_iterator<T, Ref>;
using Node = list_node<T>;
Node* _node;
list_iterator(Node* node)
:_node(node)
{}
Ref operator*()
{
return _node->_data;
}
Self& operator++()
{
_node = _node->_next;
return *this;
}
Self operator++(int)
{
Self tmp(*this);
_node = _node->_next;
return tmp;
}
Self& operator--()
{
_node = _node->_prev;
return *this;
}
Self operator--(int)
{
Self tmp(*this);
_node = _node->_prev;
return tmp;
}
bool operator!=(const Self& s) const
{
return _node != s._node;
}
bool operator==(const Self& s) const
{
return _node == s._node;
}
};
template<class T>
class list
{
using Node = list_node<T>;
public:
using iterator = list_iterator<T, T&>;
using const_iterator = list_iterator<T, const T&>;
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;
}
list()
{
empty_init();
}
list(initializer_list<T> il)
{
empty_init();
for (auto& e : il)
{
push_back(e);
}
}
template <class InputIterator>
list(InputIterator first, InputIterator last)
{
empty_init();
while(first != last)
{
push_back(*first);
++first;
}
}
list(size_t n, T val = T())
{
empty_init();
for (size_t i = 0; i < n; ++i)
{
push_back(val);
}
}
list(int n, T val = T())
{
empty_init();
for (int i = 0; i < n; ++i)
{
push_back(val);
}
}
~list()
{
clear();
delete _head;
_head = nullptr;
_size = 0;
}
list(const list<T>& lt)
{
empty_init();
for (auto& e: lt)
{
push_back(e);
}
}
list<T>& operator=(const list<T>& lt)
{
if (this != <)
{
clear();
for (auto& e : lt)
{
push_back(e);
}
}
return *this;
}
void swap(list<T>& lt)
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}
void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}
void push_back(const T& x)
{
insert(end(), x);
}
void push_front(const T& x)
{
insert(begin(), x);
}
void pop_back()
{
erase(--end());
}
void pop_front()
{
erase(begin());
}
void insert(iterator pos, const T& x)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* newnode = new Node(x);
prev->_next = newnode;
newnode->_prev = prev;
newnode->_next = cur;
cur->_prev = newnode;
++_size;
}
iterator erase(iterator pos)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;
prev->_next = next;
next->_prev = prev;
delete cur;
--_size;
return iterator(next);
}
size_t size() const
{
return _size;
}
private:
Node* _head;
size_t _size = 0;
};
}
test.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<algorithm>
#include<vector>
#include<list>
#include"List.h"
using namespace std;
void test_op1()
{
srand(time(0));
const int N = 1000000;
list<int> lt1;
vector<int> v;
for (int i = 0; i < N; ++i)
{
auto e = rand() + i;
lt1.push_back(e);
v.push_back(e);
}
int begin1 = clock();
sort(v.begin(), v.end());
int end1 = clock();
int begin2 = clock();
lt1.sort();
int end2 = clock();
printf("vector sort:%d\n", end1 - begin1);
printf("list sort:%d\n", end2 - begin2);
}
void test_op2()
{
srand(time(0));
const int N = 1000000;
list<int> lt1;
list<int> lt2;
for (int i = 0; i < N; ++i)
{
auto e = rand() + i;
lt1.push_back(e);
lt2.push_back(e);
}
int begin1 = clock();
vector<int> v(lt2.begin(), lt2.end());
sort(v.begin(), v.end());
lt2.assign(v.begin(), v.end());
int end1 = clock();
int begin2 = clock();
lt1.sort();
int end2 = clock();
printf("list copy vector sort copy list sort:%d\n", end1 - begin1);
printf("list sort:%d\n", end2 - begin2);
}
void test_list1()
{
bit::list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
bit::list<int>::iterator it = lt.begin();
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
}
void test_list2()
{
bit::list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_front(-1);
lt.push_front(-2);
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
lt.pop_back();
lt.pop_back();
lt.pop_front();
lt.pop_front();
for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
cout << lt.size() << endl;
}
void Print(const bit::list<int>& lt)
{
bit::list<int>::const_iterator it = lt.begin();
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
void test_list3()
{
bit::list<int> lt1 = { 1,2,3,4,5,6 };
for (auto e : lt1)
{
cout << e << " ";
}
cout << endl;
bit::list<int> lt2(lt1);
for (auto e : lt2)
{
cout << e << " ";
}
cout << endl;
bit::list<int> lt3 = { 10,20,30};
lt1 = lt3;
for (auto e : lt1)
{
cout << e << " ";
}
cout << endl;
Print(lt1);
}
int main()
{
test_list3();
return 0;
}
文末小结: STL 的精髓就是容器、迭代器、算法解耦。vector 让我们看到连续空间的优势,list 让我们真正理解迭代器是一种抽象,不是指针本身。这也是面试中 C++ 基础高频题,手写 list 和迭代器。