C++中的list是双向链表容器,支持高效插入删除。需包含头文件<list>,常用操作有push_back、push_front、insert、pop_back、pop_front、erase、remove等,通过front和back访问首尾元素,使用迭代器遍历,调用sort排序,reverse反转,注意不支持下标访问。

C++中的list是STL(标准模板库)提供的一个双向链表容器,支持高效的插入和删除操作。它不像数组或vector那样支持随机访问,但在任意位置插入和删除元素的时间复杂度为O(1),非常适合频繁修改数据结构的场景。
使用list前需要包含对应的头文件,并声明所需类型的list对象:
#include <list>
#include <iostream>
using namespace std;
int main() {
list<int> my_list; // 创建一个空的int类型双向链表
list<string> str_list(3, "hello"); // 创建包含3个"hello"的链表
}
list提供了丰富的成员函数来操作链表元素:
push_back(x):在末尾添加元素xpush_front(x):在开头添加元素xinsert(iter, x):在迭代器指向位置前插入xpop_back():删除最后一个元素pop_front():删除第一个元素erase(iter):删除迭代器指向的元素remove(x):删除所有值等于x的元素front():返回第一个元素的引用back():返回最后一个元素的引用size():返回元素个数empty():判断是否为空clear():清空所有元素reverse():反转链表sort():对链表排序(必须调用成员函数sort)由于list不支持下标访问,通常使用迭代器进行遍历:
立即学习“C++免费学习笔记(深入)”;
list<int> nums = {1, 2, 3, 4, 5};
// 正向遍历
for (auto it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
// 反向遍历
for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
cout << *rit << " ";
}
// C++11范围for循环
for (int n : nums) {
cout << n << " ";
}
下面是一个综合使用的例子:
#include <list>
#include <iostream>
using namespace std;
int main() {
list<int> lst;
lst.push_back(10);
lst.push_front(5);
lst.push_back(20);
cout << "Size: " << lst.size() << endl;
cout << "Front: " << lst.front() << endl;
cout << "Back: " << lst.back() << endl;
lst.sort();
lst.reverse();
cout << "After sort and reverse: ";
for (int n : lst) {
cout << n << " ";
}
cout << endl;
return 0;
}
list的插入、删除、遍历和排序操作,就能应对大多数需要高效增删的场景。注意不要用下标访问,也不要试图获取元素地址,这是双向链表的限制。以上就是C++如何使用list双向链表_C++ list双向链表使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号