特点
- 单向链表结构:只支持从前向后的遍历,节点只有“next”指针,没有“prev”。
- 轻量节省空间:比
std::list 少一半指针空间(没有前向指针)。
- 不支持 size() 操作:链表没有
size() 成员函数(遍历才能得知大小)。
- 高效前插与删除:
push_front、insert_after、erase_after 等操作 O(1)。
- 不支持随机访问和反向遍历:不能用
[]、at()、rbegin()。
- 迭代器是 ForwardIterator,只能 ++ 向后走。
初始化方式
🔹1. 默认构造
std::forward_list<int> fl; // 空链表
🔹2. 指定大小
std::forward_list<int> fl(5); // 5 个默认元素(int 为 0)
🔹3. 指定大小与初始值
std::forward_list<int> fl(3, 99); // {99, 99, 99}
🔹4. 初始化列表(C++11)
std::forward_list<int> fl = {1, 2, 3, 4};
🔹5. 区间构造
std::vector<int> v = {1, 2, 3};
std::forward_list<int> fl(v.begin(), v.end());
🔹6. 拷贝 / 移动构造
std::forward_list<int> a = {1, 2, 3};
std::forward_list<int> b(a); // 拷贝
std::forward_list<int> c(std::move(a)); // 移动