首页 文章资讯内容详情

C ++ STL中堆栈的push()和pop()方法使用

2026-06-04 1 花语

在本文中,我们将讨论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