C++ Stack 中的 emplace函数

首页 / C++入门教程 / C++ Stack 中的 emplace函数

C ++堆栈emplace()函数在当前顶部元素上方的堆栈顶部添加一个新元素。现在,我们有了一个已经存在元素的堆栈,我们希望在堆栈中插入或推送一个新元素,为此我们使用了此功能。

句法

template <class... Args> void emplace (Args&&... args);

参量

args strong>:该参数转发用于构造新元素的参数。也就是说,由args指定的元素将插入到当前顶部元素上方的堆栈中。现在,新插入的元素成为顶部元素,并且所有推入和弹出操作都在其上执行。

返回值

该函数仅用于添加新元素,并且不返回任何值。因此,该函数的返回类型为void。

例子1

//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明emplace函数的用法。

无涯教程网

#include<iostream>
#include<stack>
#include<string>
int main()
{
	std: : stack<std: : string> newstack;
	newstack.emplace (?I am the first line?);
	newstack.emplace (?I am the second one?);
	std: :cout << ?Contents of newstack: \n?;
	while (!newstack.empty () )
	{
		std: :cout << newstack.top () << ?\n?;
		newstack.pop ();
	}
	return 0;
}

输出 strong>:

Contents of newstack:
I am the second one
I am the first line

例子2

//该程序通过将11的表格插入到,然后分别进行打印来说明emplace函数的用法。

#include<iostream>
#include<stack>
#include<string>
int main()
{
	std: : stack<std: : string> newstack;
	newstack.emplace (?11?);
	newstack.emplace (?22?);
	newstack.emplace (?33?);
	newstack.emplace (?44?);
	newstack.emplace (?55?);
	newstack.emplace (?66?);
	newstack.emplace (?77?);
	newstack.emplace (?88?);
	newstack.emplace (?99?);
	newstack.emplace (?121?);
	std: :cout << ?Contents of newstack: \n?;
	 std: :cout <<?Table of 11?;

	while (!newstack.empty () )
	{
		std: :cout << newstack.top () << ?\n?;
		newstack.pop ();
	}
	return 0;
}

输出 strong>:

Contents of newstack: 
Table of 11121
99
88
77
66
55
44
33
22
11

例子3

//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明emplace函数的用法。

无涯教程网

#include<iostream>
#include<stack>
#include<string>
int main()
{
	std::stack<std::string> newstack;
	newstack.emplace ("We are here to see the application use of emplace function in stacks");
	newstack.emplace ("The function adds new elements are the top of the stack");
	while (!newstack.empty () )
	{
		std::cout << newstack.top () << "\n";
		newstack.pop ();
	}
	return 0;
}

输出 strong>:

The function adds new elements are the top of the stack         
We are here to see the application use of emplace function in stacks 

复杂

对emplace_back进行了一次调用。该函数用于插入新元素,这是通过进行一次调用来完成的。

数据竞赛

堆栈中存在的所有元素均被修改。由于该元素被添加到顶部,因此所有其他元素的相应位置也发生了变化。

异常安全

提供与在基础容器对象上执行的操作等效的保证。





祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

代码精进之路 -〔范学雷〕

10x程序员工作法 -〔郑晔〕

许式伟的架构课 -〔许式伟〕

零基础学Java -〔臧萌〕

黄勇的OKR实战笔记 -〔黄勇〕

计算机基础实战课 -〔彭东〕

B端产品经理入门课 -〔董小圣〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)