C ++堆栈emplace()函数在当前顶部元素上方的堆栈顶部添加一个新元素。现在,我们有了一个已经存在元素的堆栈,我们希望在堆栈中插入或推送一个新元素,为此我们使用了此功能。
template <class... Args> void emplace (Args&&... args);
args strong>:该参数转发用于构造新元素的参数。也就是说,由args指定的元素将插入到当前顶部元素上方的堆栈中。现在,新插入的元素成为顶部元素,并且所有推入和弹出操作都在其上执行。
该函数仅用于添加新元素,并且不返回任何值。因此,该函数的返回类型为void。
//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明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
//该程序通过将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
//该程序通过在堆栈顶部添加两个简单的字符串并进行打印来说明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进行了一次调用。该函数用于插入新元素,这是通过进行一次调用来完成的。
堆栈中存在的所有元素均被修改。由于该元素被添加到顶部,因此所有其他元素的相应位置也发生了变化。
提供与在基础容器对象上执行的操作等效的保证。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)