有一个网站专门做民宿,公司地址怎么注册定位,选择网站建设公司好,平台设计师摘要
C 标准库中的 std::list 是一种双向链表容器#xff0c;它允许在常数时间内进行插入和删除操作#xff0c;每个元素包含一个指向前一个和后一个元素的指针。这给我们开发提供了高效的插入和删除操作。
引入头文件
要使用 std::list#xff0c;需要包含头文件 li…摘要
C 标准库中的 std::list 是一种双向链表容器它允许在常数时间内进行插入和删除操作每个元素包含一个指向前一个和后一个元素的指针。这给我们开发提供了高效的插入和删除操作。
引入头文件
要使用 std::list需要包含头文件 list
#include list创建和初始化
#include iostream
#include listint main() {std::listint l1; // 默认构造函数std::listint l2(5, 10); // 创建包含 5 个值为 10 的元素的列表std::listint l3 {1, 2, 3, 4, 5, 6}; // 列表初始化// 输出列表 l3 的内容for (int n : l3) {std::cout n ;}std::cout std::endl;return 0;
}常用方法和操作
1. 插入和删除元素
#include iostream
#include listint main() {std::listint l {1, 2, 3, 4, 5, 6};// 在末尾添加元素l.push_back(6);// 在开头添加元素l.push_front(0);// 在第三个位置插入元素auto it l.begin();std::advance(it, 3); // 前进 3 个位置l.insert(it, 99);// 删除开头的元素l.pop_front();// 删除末尾的元素l.pop_back();// 删除特定位置的元素it l.begin();std::advance(it, 2); // 前进 2 个位置l.erase(it);// 输出列表 l 的内容for (int n : l) {std::cout n ;}std::cout std::endl;return 0;
}2. 访问元素
std::list 不支持随机访问即不支持 operator[]但是可以使用迭代器遍历和访问元素
#include iostream
#include listint main() {std::listint l {1, 2, 3, 4, 5, 6};// 使用迭代器遍历for (auto it l.begin(); it ! l.end(); it) {std::cout *it ;}std::cout std::endl;// 使用范围 for 循环遍历for (int n : l) {std::cout n ;}std::cout std::endl;return 0;
}3. 反向遍历
#include iostream
#include listint main() {std::listint l {1, 2, 3, 4, 5, 6};// 反向遍历for (auto it l.rbegin(); it ! l.rend(); it) {std::cout *it ;}std::cout std::endl;return 0;
}4. 其它用法
#include iostream
#include listint main() {std::listint l {1, 2, 3, 4, 5, 6};// 获取列表大小std::cout Size: l.size() std::endl;// 检查是否为空if (l.empty()) {std::cout List is empty std::endl;} else {std::cout List is not empty std::endl;}// 清空列表l.clear();std::cout Size after clear: l.size() std::endl;return 0;
}进阶使用技巧
1. 合并和排序
#include iostream
#include listint main() {std::listint l1 {1, 3, 5, 7};std::listint l2 {2, 4, 6, 8};// 合并两个已排序的列表l1.merge(l2);// 排序l1.sort();// 反转l1.reverse();// 输出列表 l1 的内容for (int n : l1) {std::cout n ;}std::cout std::endl;return 0;
}2. 去重
#include iostream
#include listint main() {std::listint l {1, 2, 2, 3, 3, 3, 4, 5};// 必须先排序然后去重l.sort();l.unique();// 输出去重后的列表 l 的内容for (int n : l) {std::cout n ;}std::cout std::endl;return 0;
}自定义比较函数
在 sort、merge 等方法中可以传递自定义比较函数
#include iostream
#include listbool customCompare(int a, int b) {return a b; // 降序排列
}int main() {std::listint l {1, 3, 2, 5, 4};// 使用自定义比较函数排序l.sort(customCompare);// 输出排序后的列表 l 的内容for (int n : l) {std::cout n ;}std::cout std::endl;return 0;
}总结
std::list 是 C 标准库中功能强大且灵活的双向链表容器适用于需要频繁插入和删除操作的场景。在我们实际开发中根据项目的具体需求选择合适的容器比如‘std::forward_list’等可以显著提高代码性能和可维护性。
引用
std::list - cppreference.com