c++ std::forward_list使用笔记

这里写目录标题

      • [1. 包含头文件](#1. 包含头文件)
      • [2. 创建和初始化](#2. 创建和初始化)
      • [3. 添加元素](#3. 添加元素)
      • [4. 遍历元素](#4. 遍历元素)
      • [5. 删除元素](#5. 删除元素)
      • [6. 其他常用操作](#6. 其他常用操作)
      • [7. 示例代码](#7. 示例代码)
      • 输出结果
      • 总结

std::forward_list 是 C++ 标准库中的一个单向链表容器。它只支持从头部到尾部的前向遍历,因此在某些场景下比 std::list 更加高效。以下是一些 std::forward_list 的基本使用方法:

1. 包含头文件

首先需要包含 <forward_list> 头文件:

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

2. 创建和初始化

可以创建一个空的 std::forward_list,或者使用初始化列表进行初始化:

cpp 复制代码
std::forward_list<int> list1; // 创建一个空的 forward_list
std::forward_list<int> list2 = {1, 2, 3, 4, 5}; // 使用初始化列表

3. 添加元素

由于 std::forward_list 是单向链表,只能在头部插入元素,或者在某些特定位置插入元素:

cpp 复制代码
list1.push_front(10); // 在头部插入元素
list1.push_front(20); // 再次在头部插入元素

4. 遍历元素

可以使用范围 for 循环或迭代器来遍历 std::forward_list

cpp 复制代码
// 使用范围 for 循环
for (const auto& elem : list2) {
    std::cout << elem << " ";
}
std::cout << std::endl;

// 使用迭代器
for (auto it = list1.begin(); it != list1.end(); ++it) {
    std::cout << *it << " ";
}
std::cout << std::endl;

5. 删除元素

可以使用 pop_front() 删除头部的元素,或者使用 erase_after() 删除特定位置的元素:

cpp 复制代码
list1.pop_front(); // 删除头部元素

auto it = list2.before_begin(); // 获取第一个元素之前的位置
list2.erase_after(it); // 删除第一个元素

6. 其他常用操作

  • empty():检查链表是否为空。
  • clear():清空链表。
  • insert_after():在指定位置后插入元素。
cpp 复制代码
if (!list1.empty()) {
    std::cout << "list1 is not empty" << std::endl;
}

list1.clear(); // 清空链表

auto it = list2.before_begin();
list2.insert_after(it, 100); // 在第一个元素之前插入 100

7. 示例代码

以下是一个完整的示例代码:

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

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

    // 在头部插入元素
    list.push_front(0);

    // 遍历并打印元素
    for (const auto& elem : list) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // 删除第一个元素
    list.pop_front();

    // 再次遍历并打印元素
    for (const auto& elem : list) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // 在第二个元素之后插入 100
    auto it = list.begin();
    list.insert_after(it, 100);

    // 最终遍历并打印元素
    for (const auto& elem : list) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

输出结果

复制代码
0 1 2 3 4 5 
1 2 3 4 5 
1 100 2 3 4 5 

总结

std::forward_list 是一个轻量级的单向链表容器,适合在需要频繁在头部插入或删除元素的场景中使用。由于它只支持前向遍历,因此在需要双向遍历的场景中,std::list 可能更为合适。

相关推荐
ShineWinsu几秒前
对于Linux:模版方法类的解析以及socket、TcpSocket的封装
linux·c++·面试·socket·模板方法模式·封装·tcpsocket
殷忆枫1 小时前
AI笔记三十七:AI边缘端道桥安全监测系统:YOLOv8n推理与Web监控全解析
笔记·yolo
hold?fish:palm1 小时前
9 找到字符串中所有字母异位词
c++·算法·leetcode
逸模1 小时前
轻加盟模式,稳住品牌统一调性的思路
笔记·建模·公装·翻模·交底
whyTeaFo2 小时前
GAMES101: Lecture 10: Geometry 1 (Introduction) ppt笔记
笔记
啦啦啦啦啦zzzz2 小时前
算法:回溯算法
c++·算法·leetcode
Lzg_na3 小时前
订阅发布模块事例
c++
郝学胜-神的一滴3 小时前
[简化版 GAMES 104] 现代游戏引擎 02:拆解现代游戏引擎5+1层级架构,吃透引擎底层核心逻辑
c++·unity·架构·游戏引擎·图形渲染·unreal engine·系统设计
sulikey3 小时前
个人Linux操作系统学习笔记11 - 环境变量
linux·笔记·学习
汉克老师3 小时前
2026年CSP-J初赛分数线-----预测
c++·csp-j·小学生·学c++编程