FX-std::list

std::list 是 C++ 标准库中的一个双向链表容器,定义在 <list> 头文件中。它支持在任意位置高效地插入和删除元素,但不支持随机访问。以下是 std::list 的基本用法和一些常见操作:

1. 包含头文件

cpp 复制代码
#include <list>

2. 定义和初始化

cpp 复制代码
std::list<int> myList; // 定义一个空的 list
std::list<int> myList2 = {1, 2, 3, 4, 5}; // 使用初始化列表初始化

3. 插入元素

cpp 复制代码
myList.push_back(10); // 在末尾插入元素
myList.push_front(5); // 在开头插入元素

auto it = myList.begin();
std::advance(it, 2); // 移动迭代器到第3个位置
myList.insert(it, 15); // 在指定位置插入元素

4. 删除元素

cpp 复制代码
myList.pop_back(); // 删除末尾元素
myList.pop_front(); // 删除开头元素

auto it = myList.begin();
std::advance(it, 2); // 移动迭代器到第3个位置
myList.erase(it); // 删除指定位置的元素

myList.remove(10); // 删除所有值为10的元素

5. 访问元素

cpp 复制代码
int firstElement = myList.front(); // 访问第一个元素
int lastElement = myList.back(); // 访问最后一个元素

// 遍历 list
for (auto it = myList.begin(); it != myList.end(); ++it) {
    std::cout << *it << " ";
}

6. 大小和容量

cpp 复制代码
bool isEmpty = myList.empty(); // 检查是否为空
size_t size = myList.size(); // 获取元素个数

7. 排序和反转

cpp 复制代码
myList.sort(); // 对 list 进行排序
myList.reverse(); // 反转 list
cpp 复制代码
#include <iostream>
#include <list>

int main() {
    std::list<int> myList = {5, 3, 1, 4, 2};

    // 默认升序排序
    myList.sort();
    std::cout << "升序排序: ";
    for (int val : myList) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    // 自定义降序排序
    myList.sort([](int a, int b) {
        return a > b;
    });
    std::cout << "降序排序: ";
    for (int val : myList) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

8. 合并和拼接

cpp 复制代码
std::list<int> anotherList = {20, 30, 40};
myList.merge(anotherList); // 合并两个 list,合并后 anotherList 为空

myList.splice(myList.begin(), anotherList); // 将 anotherList 的元素拼接到 myList 的开头

9. 其他操作

cpp 复制代码
myList.unique(); // 删除连续重复的元素
myList.resize(10); // 调整 list 的大小

10. 示例代码

cpp 复制代码
#include <iostream>
#include <list>

int main() {
    std::list<int> myList = {1, 2, 3, 4, 5};

    myList.push_back(6);
    myList.push_front(0);

    for (auto it = myList.begin(); it != myList.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    myList.remove(3);
    myList.sort();
    myList.reverse();

    for (auto it = myList.begin(); it != myList.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

总结

std::list 是一个灵活的双向链表容器,适合频繁插入和删除操作的场景。由于它不支持随机访问,因此在需要随机访问时,std::vectorstd::deque 可能是更好的选择。

相关推荐
埃博拉酱2 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
tryCbest3 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅3 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技3 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~3 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
qq_454245033 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode