C++ STL 中的 forward_list::begin() 和 forward_list::end()
本文將討論 C++ 中 forward_list::begin() 和 forward_list::end() 函式的工作原理、語法和示例。
什麼是 STL 中的 Forward_list?
Forward list 是一種序列容器,允許在序列中的任何位置進行常數時間插入和刪除操作。Forward list 以單鏈表的形式實現。順序透過每個元素關聯到序列中下一個元素的連結來維護。
什麼是 forward_list::begin()?
forward_list::begin() 是 C++ STL 中一個內建函式,在標頭檔案中宣告。begin() 返回一個迭代器,該迭代器指向 forward_list 容器中的第一個元素。大多數情況下,我們將 begin() 和 end() 結合使用以提供 forward_list 容器的範圍。
語法
forwardlist_container.begin();
此函式不接受任何引數。
返回值
此函式返回一個指向容器第一個元素的雙向迭代器。
示例
#include <bits/stdc++.h> using namespace std; int main(){ //creating a forward list forward_list<int> forwardList = { 4, 1, 2, 7 }; cout<<"Printing the elements of a forward List\n"; //calling begin() to point to the first element for (auto i = forwardList.begin(); i != forwardList.end(); ++i) cout << ' ' << *i; return 0; }
輸出
如果我們執行上述程式碼,它將生成以下輸出
Printing the elements of a forward List 4 1 2 7
什麼是 forward_list::end()?
forward_list::end() 是 C++ STL 中一個內建函式,在標頭檔案中宣告。end() 返回一個迭代器,該迭代器指向 forward_list 容器中的最後一個元素。大多數情況下,我們將 begin() 和 end() 結合使用以提供 forward_list 容器的範圍。
語法
forwardlist_container.end();
此函式不接受任何引數。
返回值
此函式返回一個指向容器第一個元素的雙向迭代器。
示例
#include <bits/stdc++.h> using namespace std; int main(){ //creating a forward list forward_list<int> forwardList = { 4, 1, 2, 7 }; cout<<"Printing the elements of a forward List\n"; //calling begin() to point to the first element for (auto i = forwardList.begin(); i != forwardList.end(); ++i) cout << ' ' << *i; return 0; }
輸出
如果我們執行上述程式碼,它將生成以下輸出
Printing the elements of a forward List 4 1 2 7
廣告