#include <list>
using namespace std;
list<int> lst1; // 定义一个空的list,元素类型为int
list<int> lst2(10); // 定义一个大小为10的list,元素类型为int,初始值为0
list<int> lst3(10, 1); // 定义一个大小为10的list,元素类型为int,初始值为1
list<int> lst4 = {1, 2, 3}; // 使用花括号进行初始化
list<int> lst5(lst4); // 使用拷贝构造函数进行初始化
#include <list>
using namespace std;
list<int> lst = {1, 2, 3};
// 获取list的大小
int size = lst.size();
// 获取list的某个位置的元素
int element = lst.front(); // 获取第一个元素
// 修改list的某个位置的元素
lst.front() = 4; // 将第一个元素修改为4
// list的插入和删除
lst.push_back(4); // 在list的末尾插入一个元素
lst.push_front(0); // 在list的开头插入一个元素
lst.insert(lst.begin() + 1, 5); // 在list的第二个位置插入元素5
lst.erase(lst.begin() + 2); // 删除list的第三个元素
lst.pop_front(); // 删除list的第一个元素
lst.pop_back(); // 删除list的最后一个元素
// list的遍历
for (auto it = lst.begin(); it != lst.end(); ++it) {
cout << *it << " ";
}
for (int element : lst) {
cout << element << " ";
}
#include <list>
#include <algorithm>
using namespace std;
list<int> lst = {3, 1, 4, 1, 5, 9};
// list的排序
lst.sort(); // 对list进行排序
// list的查找
auto it = find(lst.begin(), lst.end(), 4); // 查找4在list中的位置
if (it != lst.end()) {
cout << "4 found at position " << distance(lst.begin(), it) << endl;
} else {
cout << "4 not found" << endl;
}
// list的拼接
list<int> lst1 = {1, 2};
list<int> lst2 = {3, 4};
lst1.splice(lst1.end(), lst2); // 将lst2中的元素插入到lst1的末尾
// list的反转
lst1.reverse(); // 反转list