stl list 使用指南:包含头文件:#include 创建 list:std::list

C++ 函数的 STL list 使用指南
STL(标准模板库)中的 list 是一个双向链表,它可以高效地插入和删除元素。本指南将介绍如何使用 list,并提供实战案例帮助你理解。
1. 包含头文件
立即学习“C++免费学习笔记(深入)”;
首先,在你的代码中包含 #include 头文件以使用 list。
2. 创建 list
要创建一个 list,可以使用以下语法:
std::listmyList;
其中 int 表示 list 中元素的类型,可以根据需要替换为其他数据类型。
3. 添加元素
有几种方法可以向 list 中添加元素:
-
push_front(value):在 list 的开头添加元素。 -
push_back(value):在 list 的末尾添加元素。 -
insert(iterator, value):在给定的迭代器之前插入元素。
myList.push_back(10); myList.push_front(5); myList.insert(myList.begin(), 15);
4. 遍历 list
可以使用迭代器遍历 list 中的元素:
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}输出:15 5 10
5. 删除元素
有两种方法可以删除 list 中的元素:
-
erase(iterator):删除由迭代器指向的元素。 -
remove(value):删除 list 中所有等于指定值的值。
myList.erase(myList.begin()); myList.remove(10);
实战案例:实现先进先出 (FIFO) 队列
使用 list 可以轻松实现 FIFO 队列:
#includeclass Queue { private: std::list
elements; public: void enqueue(int value) { elements.push_back(value); } int dequeue() { if (elements.empty()) { throw std::runtime_error("Queue is empty"); } int front = elements.front(); elements.pop_front(); return front; } bool isEmpty() { return elements.empty(); } };
你可以使用这个类来实现 FIFO 队列的行为,如下所示:
Queue myQueue;
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
while (!myQueue.isEmpty()) {
int value = myQueue.dequeue();
std::cout << value << " ";
}输出:1 2 3










