介绍
序列容器之list是一种在C++标准模板库(STL)中广泛使用的数据结构,它基于双向链表实现,提供了在常数时间内进行任意位置插入和删除操作的能力。
定义:list是一种序列容器,可以存储具有相同类型的元素序列。
底层实现:list的底层是通过双向链表实现的,每个节点包含数据部分和两个指针,分别指向前一个节点和后一个节点。
ist提供了丰富的成员函数,用于管理容器中的元素,包括:
- 插入和删除:push_front、pop_front、push_back、pop_back、insert、erase等,用于在list的头部、尾部或指定位置插入或删除元素。
- 访问元素:front、back分别用于访问list的第一个和最后一个元素。注意,由于list不支持随机访问,因此没有直接访问任意位置元素的成员函数。
- 迭代器:begin、end、rbegin、rend分别用于获取list的正向和反向迭代器,用于遍历list中的元素。
- 容量相关:size用于获取list中元素的个数,empty用于判断list是否为空。
创建和初始化
#include <iostream>
#include <list>
int main() {
// 创建一个空的list
std::list<int> lst;
// 使用初始值创建list
std::list<int> lst_with_size(5); // 创建一个包含5个元素的list,元素值为默认值0
std::list<int> lst_with_values(5, 10); // 创建一个包含5个元素的list,元素值为10
// 使用列表初始化list
std::list<int> lst_with_list = {1, 2, 3, 4, 5};
return 0;
}
添加元素
#include <iostream>
#include <list>
int main() {
std::list<int> lst;
// 在list的末尾添加元素
lst.push_back(1);
lst.push_back(2);
lst.push_back(3);
// 在list的开头添加元素
lst.push_front(0);
// 插入元素到指定位置
auto it = lst.begin();
std::advance(it, 2);
lst.insert(it, 4); // 在第三个位置插入4
for (int val : lst) {
std::cout << val << " "; // 输出: 0 1 4 2 3
}
std::cout << std::endl;
return 0;
}
访问元素
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {1, 2, 3, 4, 5};
// 访问第一个和最后一个元素
std::cout << lst.front() << std::endl; // 输出: 1
std::cout << lst.back() << std::endl; // 输出: 5
return 0;
}
遍历元素
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {1, 2, 3, 4, 5};
// 使用范围for循环遍历
for (int val : lst) {
std::cout << val << " ";
}
std::cout << std::endl;
// 使用迭代器遍历
for (auto it = lst.begin(); it != lst.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
删除元素
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {1, 2, 3, 4, 5};
// 删除第一个元素
lst.pop_front();
// 删除最后一个元素
lst.pop_back();
// 删除指定位置的元素
auto it = lst.begin();
std::advance(it, 1); // 指向第二个元素
lst.erase(it);
// 删除指定范围的元素
auto it1 = lst.begin();
auto it2 = lst.begin();
std::advance(it2, 2);
lst.erase(it1, it2); // 删除前两个元素
for (int val : lst) {
std::cout << val << " "; // 可能输出: 3 4 5
}
std::cout << std::endl;
return 0;
}
其他常用操作
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {1, 2, 3, 4, 5};
// 获取list的大小
std::cout << "Size: " << lst.size() << std::endl; // 输出: Size: 5
// 检查list是否为空
std::cout << "Is empty: " << std::boolalpha << lst.empty() << std::endl; // 输出: Is empty: false
// 清空list
lst.clear(); // 现在lst为空
for (int val : lst) {
std::cout << val << " "; // 不会输出任何东西,因为lst为空
}
std::cout << std::endl;
return 0;
}
总结
list是一种基于双向链表实现的序列容器,它提供了在常数时间内进行任意位置插入和删除操作的能力,但不支持随机访问。list的灵活性和高效性使得它在处理需要频繁插入和删除操作的场景时非常有用。