C++ STL 中的 forward_list::before_begin()
在本文中,我們將討論 C++ 中 forward_list::before_begin() 函式的工作原理、語法和示例。
什麼是 STL 中的 Forward_list?
Forward list 是一種序列容器,允許在序列中的任何位置進行常數時間插入和刪除操作。Forward list 以單鏈表的形式實現。順序透過每個元素與序列中下一個元素的連結來保持。
什麼是 forward_list::before_begin()?
forward_list::before_begin() 是 C++ STL 中一個內建函式,它在 <forward_list> 標頭檔案中宣告。before_begin() 返回一個迭代器,該迭代器指向 forward_list 容器中第一個元素之前的元素。
語法
forwardlist_container.before_begin();
此函式不接受任何引數。
返回值
此函式返回指向序列開始位置之前的迭代器。
示例
/* 在下面的程式碼中,我們建立一個 forward list,然後使用 before_begin() 函式指向 forward list 中的第一個元素,之後我們將嘗試使用 insert_after() 函式在 forward list 的前面插入一個新元素。現在,我們將注意到輸出的變化。*/
#include <bits/stdc++.h>
using namespace std;
int main() {
//creating and initializing forward list
forward_list<int> forwardList = { 3, 6, 1, 2, 4 };
//calling before_begin function
auto i = forwardList.before_begin();
//inserting element before forward list
forwardList.insert_after(i, 7);
cout<< "Element of the forward list are:" << endl;
for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
cout << *j << " ";
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
Element of the forward list are: 7 3 6 1 2 4
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
forward_list<int> forwardList = {2, 23, 12, 11};
forwardList.insert_after(forwardList.before_begin(), 19 );
cout << "Elements in the forward lists are : ";
for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
cout << *j << " ";
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出
Elements in the forward lists are : 19 2 23 12 11
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP