C++ STL 中的栈 push() 和 pop()
在本文中,我们将讨论 C++ STL 中 stack::push() 和 stack::pop() 函数的工作原理、语法和示例。
什么是 C++ STL 中的栈?
栈是一种数据结构,它以 LIFO(后进先出)的方式存储数据,我们从最后一个插入元素的顶部进行插入和删除操作。就像一叠盘子,如果我们想将一个新的盘子推入栈中,我们将其插入顶部;如果我们想从栈中移除一个盘子,我们也从顶部将其移除。
什么是 stack::push()?
stack::push() 函数是 C++ STL 中的一个内置函数,它在 <stack> 头文件中定义。push() 用于将元素推入或插入到栈容器的顶部。新元素的内容被复制并初始化。
语法
stack_name.push(value_type& val);
参数
该函数接受以下参数:
val - 我们想要推入的值
返回值
此函数不返回任何值。
输入
std::stack<int> stack1; stack1.push(1); stack1.push(2); stack1.push(3);
输出
3 2 1
示例
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int>stck;
int Product = 1;
stck.push(1);
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
while (!stck.empty()){
Product = Product * stck.top();
cout<<"\nsize of stack is: "<<stck.size();
stck.pop();
}
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
size of stack is: 6 size of stack is: 5 size of stack is: 4 size of stack is: 3 size of stack is: 2 size of stack is: 1
什么是 stack::pop()?
stack::pop() 函数是 C++ STL 中的一个内置函数,它在 <stack> 头文件中定义。pop() 用于弹出或从栈容器的顶部移除一个元素。顶部的内容被移除,容器的大小减少 1。
语法
stack_name.pop();
参数
该函数不接受任何参数。
返回值
此函数不返回任何值。
输入
std::stack<int> stack1; stack1.push(1); stack1.push(2); stack1.push(3); stack1.pop();
输出
2 1
示例
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> stck;
int Product = 1;
stck.push(1);
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
while (!stck.empty()){
Product = Product * stck.top();
cout<<"\nsize of stack is: "<<stck.size();
stck.pop();
}
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
size of stack is: 6 size of stack is: 5 size of stack is: 4 size of stack is: 3 size of stack is: 2 size of stack is: 1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP