热门问题
时间线
聊天
视角
前向列表
来自维基百科,自由的百科全书
Remove ads
前向列表(英语:forward list)[1]是于标准模板函数库中的序列容器(sequence containers),以单向链表实现,自C++11标准开始被定义于C++标准函数库里的 <forward_list>
头文件[2]。
此条目需要补充更多来源。 (2024年3月22日) |
与 std::list
相比,原本 std::list
是一个双向链表,每个节点都有指向上一个节点与下一个节点的指针,所以可以双向遍历,但这样会使得内存空间消耗得更多,速度会相对地变慢。但 std::forward_list
提供了不需要双向迭代时,更节省存储空间的容器。
std::forward_list
的优点是能够支持在容器中的任何位置更快速地插入、移除、提取与移动元素。但因为它是以单向链表实现,因此不支持随机存取,须以线性时间来走访。
模板
template<
class T,
class Allocator = std::allocator<T>
> class forward_list
namespace pmr {
template< class T >
using forward_list = std::forward_list<T, std::pmr::polymorphic_allocator<T>>;
}
成员类型
Remove ads
成员函数
C++ 代码实例
# include <iostream>
# include <forward_list> // 導入前向串列標頭檔
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
}
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
auto it = list1.begin();
std::advance(it, 2);
list1.insert_after(it, 5);
// list1 = {1, 2, 3, 5, 4}
}
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 3, 4};
list1.remove(3);
// list1 = {1, 2, 4}
}
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
list1.reverse();
// list1 = {4, 3, 2, 1}
}
基于效率考量,std::forward_list
不提供 size()
的方法。取而代之,得到成员个数需使用std::distance(_begin, _end)
。
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
std::cout << "Size of list1: " << std::distance(list1.begin(), list1.end()) << std::endl;
}
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
std::forward_list<int> list2;
// 使用 assign_range 將 list1 中的元素賦值給 list2
list2.assign_range(list1.begin(), list1.end());
// list2 現在包含與 list1 相同的元素
}
# include <iostream>
# include <forward_list>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
auto it = list1.begin();
std::advance(it, 2);
// 在位置 it 的後面原地建構元素 5
list1.emplace_after(it, 5);
// list1 = {1, 2, 3, 5, 4}
}
# include <iostream>
# include <forward_list>
# include <vector>
int main(){
std::forward_list<int> list1 = {1, 2, 3, 4};
std::vector<int> vec = {5, 6, 7};
auto it = list1.begin();
std::advance(it, 2);
// 在位置 it 的後面插入 vec 中的元素
list1.insert_range_after(it, vec.begin(), vec.end());
// list1 = {1, 2, 3, 5, 6, 7, 4}
}
# include <iostream>
# include <forward_list>
# include <vector>
int main(){
std::forward_list<int> list1 = {3, 4, 5};
std::vector<int> vec = {1, 2};
// 在開始處加入 vec 中的元素
list1.prepend_range(vec.begin(), vec.end());
// list1 = {1, 2, 3, 4, 5}
}
参考文献
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads