list
是 C++ 标准库中的双向链表容器。
list初始化示例:
#include <list>int n = 7;std::list<int> lst; // 初始化一个空的双向链表 lststd::list<int> lst(n); // 初始化一个大小为 n 的链表 lst,链表中的值默认都为 0std::list<int> lst{1, 3, 5}; // 初始化一个包含元素 1, 3, 5 的链表 lststd::list<int> lst(n, 2); // 初始化一个大小为 n 的链表 lst,其中值都为 2
list常用操作示例:
#include <iostream>
#include <list>
using namespace std;int main() {list<int> lst{1, 2, 3, 4, 5}; // 初始化链表cout << lst.empty() << endl; // 检查链表是否为空,输出:falsecout << lst.size() << endl; // 获取链表的大小,输出:5lst.push_front(0); // 在链表头部插入元素 0lst.push_back(6); // 在链表尾部插入元素 6cout << lst.front() << " " << lst.back() << endl; // 获取链表头部和尾部元素,输出:0 6lst.pop_front(); // 删除链表头部元素lst.pop_back(); // 删除链表尾部元素auto it = lst.begin(); // 在链表中插入元素advance(it, 2); // 移动到第三个位置lst.insert(it, 99); // 在第三个位置插入 99it = lst.begin(); // 删除链表中某个元素advance(it, 1); // 移动到第二个位置lst.erase(it); // 删除第二个位置的元素// 遍历链表// 输出:1 99 3 4 5for (int val : lst) {cout << val << " ";}cout << endl;return 0;
}
一般情况下,我们在头部增删元素会使用双链表,因为他在头部增删元素的效率比vector高。但我们通过索引访问元素时一般会使用vector。