前向列表

前向串列()是於標準樣板函式庫中的序列容器(sequence containers),以單向鏈結串列實現,自C++11標準開始被定義於C++標準函式庫裡的 標頭檔。

與 std::list 相比,原本 std::list 是一個雙向鏈結串列,每個節點都有指向上一個節點與下一個節點的指標,所以可以雙向遍歷,但這樣會使得內存空間消耗得更多,速度會相對地變慢。但 std::forward_list 提供了不需要雙向迭代時,更節省儲存空間的容器。

std::forward_list 的優點是能夠支援在容器中的任何位置更快速地插入、移除、提取與移動元素。但因為它是以單向鏈結串列實現,因此不支援隨機存取,須以線性時間來走訪。

模板
自C++11
template

class forward_list

自C++17
namespace pmr {
template
using forward_list = std::forward_list>;
}

成員類型
成員函式
成員存取
迭代器
容量
修飾語
操作
C++ 程式碼實例
建構

include

include // 導入前向串列標頭檔

int main(){
std::forward_list list1 = {1, 2, 3, 4};
}

插入元素

include

include

int main(){
std::forward_list 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

include

int main(){
std::forward_list list1 = {1, 2, 3, 3, 4};
list1.remove(3);
// list1 = {1, 2, 4}
}

反轉串列

include

include

int main(){
std::forward_list list1 = {1, 2, 3, 4};
list1.reverse();
// list1 = {4, 3, 2, 1}
}

取得長度
基於效率考量,std::forward_list 不提供 size() 的方法。取而代之,得到成員個數需使用std::distance(_begin, _end)。

include

include

int main(){
std::forward_list list1 = {1, 2, 3, 4};
std::cout

指定範圍(C++23)

include

include

int main(){
std::forward_list list1 = {1, 2, 3, 4};
std::forward_list list2;

// 使用 assign_range 將 list1 中的元素賦值給 list2
list2.assign_range(list1.begin(), list1.end());

// list2 現在包含與 list1 相同的元素
}

原地建構

include

include

int main(){
std::forward_list 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}
}

插入範圍(C++23)

include

include

include

int main(){
std::forward_list list1 = {1, 2, 3, 4};
std::vector 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}
}

前置範圍(C++23)

include

include

include

int main(){
std::forward_list list1 = {3, 4, 5};
std::vector vec = {1, 2};

// 在開始處加入 vec 中的元素
list1.prepend_range(vec.begin(), vec.end());
// list1 = {1, 2, 3, 4, 5}
}

參考文獻

评论 (0)

  • 还没有评论,来抢沙发吧。