1.list的介绍
- List 是 C++ STL(Standard Template Library)中的一种容器,用于存储一系列的元素。
- 它是一个双向链表,可以在任意位置高效地插入和删除元素,相比于数组,list 的插入和删除操作的时间复杂度为 O(1)。
- List 中的元素不会在内存中连续存储,而是通过指针相连,每个元素都包含前一个元素和后一个元素的指针。
- List 中的迭代器支持双向移动,可以高效地遍历整个列表。
2.list的使用
list的定义方式
list<int> lt1; //构造int类型的空容器
list<int> lt2(10, 2); //构造含有10个2的int类型容器
list<int> lt3(lt2); //拷贝构造int类型的lt2容器的复制品
string s("hello world");
list<char> lt4(s.begin(),s.end()); //构造string对象某段区间的复制品
int arr[] = { 1, 2, 3, 4, 5 };
int sz = sizeof(arr) / sizeof(int);
list<int> lt5(arr, arr + sz); //构造数组某段区间的复制品
插入元素
lt1.push_back(10); // 在list末尾插入元素
lt1.push_front(20); // 在list开头插入元素
删除元素
lt1.pop_back(); // 删除list末尾的元素
lt1.pop_front(); // 删除list开头的元素
插入和删除指定位置元素
auto it = myList.begin(); // 获取list的迭代器
++it; // 移动迭代器到下一个位置
lt1.insert(it, 15); // 在指定位置插入元素
lt1.erase(it); // 删除指定位置的元素
List的迭代器使用
使用迭代器遍历list:
for (auto it = lt1.begin(); it != lt1.end(); ++it) {
cout << *it << " "; // 输出当前元素的值
}
反向遍历list:
for (auto rit = lt1.rbegin(); rit != lt1.rend(); ++rit) {
cout << *rit << " "; // 逆序输出当前元素的值
}
List的大小控制
获取list的大小:
cout << "Size of list: " << lt1.size() << endl;
调整list的大小:
lt1.resize(10); // 调整list的大小为10,多出的元素用默认值填充
判断list是否为空:
if (lt1.empty()) {
cout << "List is empty" << endl;
} else {
cout << "List is not empty" << endl;
}
清空list:
lt1.clear(); // 清空list
List的操作函数
排序:
lt1.sort(); // 对list进行升序排序
合并两个list:
list<int> lt2 = {5, 3, 7};
lt1.merge(lt2); // 将lt2合并到lt1中,要求两个list已经是有序的
删除指定值的元素:
lt1.remove(5); // 删除list中值为5的元素
删除满足条件的元素:
lt1.remove_if([](int x) {
return x % 2 == 0; // 返回真表示删除偶数元素
});
将相邻的重复元素合并:
lt1.unique(); // 合并相邻的重复元素,只保留一个
将另一个list的元素合并到当前list的指定位置:
auto it = lt1.begin();
++it; // 移动到第二个元素位置
lt1.splice(it, lt2); // 将myList2合并到myList的指定位置
反转list:
lt1.reverse(); // 反转list中的元素顺序
赋值:
lt1.assign(5, 100); // 将list的元素替换为5个值为100的元素
交换两个list的内容:
list<int> lt2 = {1, 2, 3};
lt1.swap(lt2); // 交换myList和myList2的内容