C++ STL 中的栈 (3.5)
在 C++ STL 中,栈用作容器,其实现为 LIFO 结构。LIFO 表示后进先出。可以将栈想象成一堆书,书一本叠在一本上面,最后放入的书将首先被移除,这就是为什么它被称为 LIFO 结构。

与栈相关的操作有:
top() - 此函数返回对栈顶元素的引用。
语法 - name_of_stack.top()
参数 - 无参数
返回值 - 对栈容器顶端元素的引用
push() - 此函数用于将元素插入到栈容器中。
语法 - name_of_stack.push(element)
参数 - 此函数接受要插入的元素。
返回值 - 它不返回任何值。
pop() - 此函数用于从栈容器中移除元素。
语法 - name_of_stack.pop()
参数 - 无参数
返回值 - 它移除栈顶元素并返回它。
size() - 此函数用于计算栈中存在的元素总数。
语法 - name_of_stack.size()
参数 - 无参数
返回值 - 它返回栈中元素的数量。
empty() - 此函数用于检查栈是否为空。
语法 - name_of_stack.empty()
参数 - 无参数
返回值 - 它返回布尔值 true 或 false。栈为空时为 true,栈不为空时为 false。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a stack container
stack <int> newStack;
//insert elements to a stack
newStack.push(10);
newStack.push(20);
newStack.push(30);
newStack.push(40);
//check whether the values are pushed in stack or not
//using empty()
if(!newStack.empty()){
//calculate size of a stack
cout<<"Stack size is: "<< newStack.size();
}
else{
cout<<"Stack is empty";
}
cout<<"\nElements in the stack are:";
while(!newStack.empty()){
cout<<" "<< newStack.top();
newStack.pop();
}
return 0;
}输出
Stack size is: 4 Elements in the stack are: 40 30 20 10
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP