欢迎来到C++系列教程第十二节。本节我们将深入探讨C++标准模板库(STL)中的list容器。list是一个双向链表,它允许在常数时间内进行插入和删除操作。无论你是初学者还是希望巩固知识的开发者,本文都将详细讲解list介绍、list使用以及list模拟实现,帮助你全面掌握C++ list。
list是C++ STL中的序列式容器,底层实现为双向循环链表(通常带有一个头节点)。与vector不同,list中的元素在内存中不是连续存储的,而是通过指针链接。这种结构使得list在任意位置插入和删除元素非常高效,时间复杂度为O(1),但随机访问(如operator[])不被支持,访问第i个元素需要遍历链表,时间复杂度为O(n)。
list的头文件是,定义在命名空间std中。一个典型的list节点包含数据域和指向前后节点的指针。
list提供了多种构造函数:
list lst; 构造空listlist lst(n, val); 构造包含n个val的listlist lst(begin, end); 用迭代器区间构造list lst(const list& other); 拷贝构造示例:list
list的迭代器是双向迭代器,支持++和--操作,但不支持随机访问。常用函数有begin(), end(), rbegin(), rend()等。
empty():判断是否为空size():返回元素个数(C++11前为O(n),C++11后为O(1))front()、back():访问首尾元素push_back(val)、push_front(val):尾插/头插pop_back()、pop_front():尾删/头删insert(pos, val):在pos位置前插入valerase(pos):删除pos位置元素clear():清空listlist还提供了一些特有操作,如splice(转移元素)、remove(移除特定值)、unique(去重)、merge(合并有序链表)、sort(排序)、reverse(反转)等。
理解list的最好方式是自己实现一个简化版。我们将从节点设计、迭代器封装到list类逐步构建。
templatestruct ListNode { ListNode* prev; ListNode* next; T data; ListNode(const T& val = T()) : prev(nullptr), next(nullptr), data(val) {}}; 迭代器需要支持基本操作:解引用、递增、递减、比较等。我们可以设计一个迭代器类模板。
templatestruct ListIterator { typedef ListNode* NodePtr; typedef ListIterator Self; NodePtr _node; ListIterator(NodePtr node = nullptr) : _node(node) {} Ref operator*() { return _node->data; } Ptr 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& it) const { return _node == it._node; } bool operator!=(const Self& it) const { return _node != it._node; }}; templateclass list { typedef ListNode Node; Node* _head; // 头节点,不存储数据public: typedef ListIterator iterator; typedef ListIterator const_iterator; // 构造函数、析构函数、拷贝控制等}; 以push_back为例:
void push_back(const T& val) { Node* newNode = new Node(val); Node* tail = _head->prev; tail->next = newNode; newNode->prev = tail; newNode->next = _head; _head->prev = newNode;} 其他函数如insert、erase、迭代器操作等类似,需注意边界情况。
本文全面介绍了C++ list的list介绍、常用接口的list使用,并给出了list模拟实现的核心代码。希望通过本教程,你能深入理解list的原理,并在实际开发中灵活运用。下一节我们将探讨其他容器,敬请期待!
本文由主机测评网于2026-02-14发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20260225201.html