C++ STL 中的 stack emplace()
在本文中,我们将讨论 C++ STL 中 stack::emplace() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Stack?
栈是一种后进先出 (LIFO) 的数据结构,我们在栈的顶部进行插入和删除操作,最后一个插入的元素位于顶部。就像一堆盘子一样,如果我们想在栈中添加一个新的盘子,我们把它放在顶部;如果我们想从栈中移除一个盘子,我们也从顶部移除。
什么是 stack::emplace()?
stack::emplace() 函数是 C++ STL 中的内置函数,它在 `
当我们运行此函数时,它会在栈的顶部插入一个新元素,并将新插入的元素设为顶部元素。此函数调用 emplace_back 函数,在顶部插入新元素。
语法
stack_name.emplace(Args& args);
参数
此函数接受以下参数:
**args** - 这些是我们想要放置的参数。
返回值
此函数不返回任何值。
**输入**
std::stack<int> stack1; stack1.emplace(1); stack1.emplace(2); stack1.emplace(3);
**输出**
3 2 1
示例
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> stck;
stck.emplace(10);
stck.emplace(20);
stck.emplace(30);
stck.emplace(40);
stck.emplace(50);
stck.emplace(60);
cout << "Elements in stack are: ";
while (!stck.empty()){
cout<<stck.top() << " ";
stck.pop();
}
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Elements in stack are: 60 50 40 30 20 10
示例
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> stck;
int total = 0;
stck.emplace(10);
stck.emplace(20);
stck.emplace(30);
stck.emplace(40);
stck.emplace(50);
stck.emplace(60);
cout << "Elements in stack are: ";
while (!stck.empty()){
cout<<stck.top() << " ";
stck.pop();
total++;
}
cout<<"\nTotal number of elements in stack are: "<<total;
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Elements in stack are: 60 50 40 30 20 10 Total number of elements in stack are: 6
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP