C++ STL 中的 forward_list emplace_after() 和 emplace_front()
本任務旨在展示 c++ 中 forward_list::emplace_after() 和 forward_list::emplace_front() 函式的工作原理。
與普通的列表不同,forward_list 只維護與下一個元素的連結,而普通列表則同時維護與下一個和上一個元素的連結,這使得可以在兩個方向上進行迭代。但 forward_list 只能向前迭代。
forward_list::emplace_after() 和 forward_list::emplace_front() 函式是 c++ 標準庫的一部分。
forward_list::emplace_after() 函式用於在列表中指定位置的元素之後插入一個新元素。
forward_list::emplace_front() 函式用於在列表的開頭插入一個元素。
需要包含 <forward_list> 標頭檔案才能呼叫該函式。
forward_list::emplace_after()
語法
Forward_List_Name.emplace_after(iterator , element);
引數
該函式接受兩個引數:
**迭代器**,迭代器包含要放置新元素的位置。
**元素**,它包含要放置的元素。
返回值
該函式返回一個迭代器,該迭代器指向已放置在 forward list 中的新元素。
forward_list::emplace_front()
語法
Forward_List_Name.emplace_front(element);
引數
該函式接受一個引數。
返回值
該函式不返回任何值。
示例
Input: 11,34,56 Output: 41 11 34 56
**解釋** -
這裡我們建立了一個包含元素 11、34、56 的 forward list Lt。然後我們呼叫了 emplace_front() 函式,該函式用於在 forward list 的開頭插入一個新元素,這裡該元素為 41。
因此,當我們列印 forward list 時,生成的輸出為 41 11 34 56,第一個元素為 41。
**以下程式中使用的步驟如下:**
- 首先建立一個列表,例如名為“Lt”的 int 型別列表,併為其分配一些值。
- 然後呼叫函式 emplace_front() 將一個新元素放置在列表的開頭。
- 然後建立一個 auto 型別的物件,例如“itr”,它將用作我們的迭代器以儲存要傳遞給 emplace_after() 函式的位置,新元素將放置在其旁邊。為 itr 指定一個位置,例如列表的末尾。
- 然後呼叫 emplace_after() 函式在指定位置插入元素。第一個引數應該是迭代器“itr”,它指定列表中的位置,第二個引數應該是要放置在該位置的元素。
演算法
Start
Step 1->In function main()
Initialize forward_list<int> Lt={}
Call function Lt.emplace_front()
Initialize auto itr=Lt.end();
Call Lt.emplace_after(itr , element)
End
Stop示例
#include<iostream>
#include<list>
using namespace std;
int main() {
forward_list<int> Lt = { 5,6,7,8 };
//Using the emplace_front() function to place element at the beginning.
Lt.emplace_front(3);
auto itr = Lt.end();
/*Using the emplace_after() function to place an element after the location specified*/
Lt.emplace_after(itr , 10)
//Displaying the list
for(auto itr = Lt.begin() ; itr!=Lt.end ; itr++)
cout<<” *itr ”<<” ”;
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
3 5 6 7 8 10
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP