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