亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

掌握 C++ std::list:语法、函数与实战示例

什么是 std::list?

在 C++ 中,std::list 是一种序列容器,以双向链表形式存储元素。这种结构允许在常数时间内于任意位置插入或删除元素,并支持双向迭代。虽然它不像 std::vector 那样提供快速随机访问,但在频繁插入或删除的场景下表现出色。

容器通过分配器自动管理内存,因此可以在运行时从两端动态增长或收缩。

为什么使用 std::list?

定义列表

要使用 std::list,需包含 <list> 头文件:

#include <list> // 模板定义
// template<class T, class Alloc = std::allocator<T>> class list;

参数说明:

示例 1:基本遍历

#include <iostream>
#include <list>
int main() {
    std::list<int> my_list{12, 5, 10, 9};
    for (int x : my_list) {
        std::cout << x << '\n';
    }
}

输出:

掌握 C++ std::list:语法、函数与实战示例

常用 std::list 操作

函数说明
insert()在迭代器位置前插入元素。
push_back()在末尾添加元素。
push_front()在开头添加元素。
pop_front()移除首个元素。
size()返回元素数量。
front()访问首个元素。
back()访问最后一个元素。
reverse()反转元素顺序。
merge()将两个已排序的列表合并为一个。

构造函数

示例 2:构造函数变体

#include <iostream>
#include <list>
int main() {
    std::list<int> l; // 空列表
    std::list<int> l1{10, 20, 30};
    std::list<int> l2(l1.begin(), l1.end()); // 范围拷贝
    std::list<int> l3(std::move(l1)); // 移动
    std::cout << "Size of l: " << l.size() << '\n';
    std::cout << "Contents of l2:\n";
    for (int x : l2) std::cout << x << '\n';
    std::cout << "Contents of l3:\n";
    for (int x : l3) std::cout << x << '\n';
}

输出:

掌握 C++ std::list:语法、函数与实战示例

容器特性

插入元素

使用 push_front、push_back 或 insert 添加元素。

示例 3:混合插入

#include <algorithm>
#include <iostream>
#include <list>
int main() {
    std::list<int> my_list{12, 5, 10, 9};
    my_list.push_front(11); // 头部
    my_list.push_back(18); // 尾部
    auto it = std::find(my_list.begin(), my_list.end(), 10);
    if (it != my_list.end()) {
        my_list.insert(it, 21); // 在 10 之前插入
    }
    for (int x : my_list) std::cout << x << '\n';
}

输出:

掌握 C++ std::list:语法、函数与实战示例

删除元素

使用 erase 移除单个元素或范围。

示例 4:擦除演示

#include <iostream>
#include <list>
int main() {
    std::list<int> my_list{12, 5, 10, 9};
    std::cout << "删除前:\n";
    for (int x : my_list) std::cout << x << '\n';
    my_list.erase(my_list.begin()); // 移除首个
    std::cout << "删除后:\n";
    for (int x : my_list) std::cout << x << '\n';
}

输出:

掌握 C++ std::list:语法、函数与实战示例

核心要点

C语言

  1. C++ 运算符全解析:类型、示例与示例程序
  2. C++ do-while 循环详解:语法、实战示例与嵌套循环
  3. 掌握 C++ switch-case:语法、用法与实战示例
  4. C++ 动态数组分配实战指南:new/delete、初始化、扩容与内存管理
  5. C++ 指针精通:核心概念、代码示例与实战应用
  6. C++ 运算符重载实战指南:语法、方法、限制与代码示例
  7. C++ 结构体详解:定义、初始化、指针、函数参数与局限性
  8. C++ 函数详解:从声明到调用的实战指南
  9. C++ Struct 与 Class 核心差异、语法及最佳实践
  10. Python collections.Counter:高效计数、更新与算术运算
  11. Python list.count() 专家指南:语法、示例与性能解析
  12. Python list.index() 详解:查找元素位置的实用指南与示例