stl标准模板库
堆叠在数据结构中 (Stack in data structure)
The stack is an ordered list where insertion and deletion are done from the same end, top. The last element that entered first is the first one to be deleted (the basic principle behind the LIFO). That means it is a data structure which is implemented as LIFO.
堆栈是一个有序列表,其中插入和删除是从同一端top进行的 。 首先输入的最后一个元素是要删除的第一个元素(LIFO的基本原理)。 这意味着它是一个实现为LIFO的数据结构。
The main stack operations are (basic ADT operations):
主要堆栈操作为(基本ADT操作):
push (T data): Insertion at top
推送(T数据):在顶部插入
T pop(): Deletion from top
T pop():从顶部删除
bool isEmpty(): Checks for stack to be empty
bool isEmpty():检查堆栈为空
Here, T is the datatype (int/char/float etc)
在这里, T是数据类型( int / char / float等)
STL (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. Therefore STACK can be implemented with help of STL too.
标准模板库(STL)是一组C ++模板类,用于提供常见的编程数据结构和功能,例如列表,堆栈,数组等。因此,也可以在STL的帮助下实现STACK。
STL中的堆栈 (STACK in STL)
To declare a stack of datatype T:
声明数据类型T的堆栈:
stack<T> st; //basic STL declarations
e.g.:
stack<int> st; //stack to hold integers only
To declare the stack iterator:
声明堆栈迭代器:
stack<T>::iterator it;
e.g.:
stack<int>::iterator it;
C ++ STACK函数 (C++ STACK functions)
push(T item) - Inserts an item on top
push(T item) -在顶部插入一个项目
pop() - Pops the top element, it doesn’t return the popped item
top() - Returns the top element
top() -返回顶部元素
empty - Returns true or false based on whether stack is empty
空 -根据堆栈是否为空返回true或false
size() - Returns size of the stack
size() -返回堆栈的大小
You can click on each function to check detailed code and implementation of each function. Below is the assemble of a total stack operation.
您可以单击每个功能以检查每个功能的详细代码和实现。 以下是总堆栈操作的汇编。
C++ stack implementation
C ++堆栈实现
#include <bits/stdc++.h>
using namespace std;
int main(){
cout<<"...STACK STL...\n";
stack<int> st; //declare the stack
cout<<"enter 0 to stop pushing else enter any other integer\n";
int num,count=0;
cin>>num;
while(num!=0){
st.push(num); //push function
cin>>num;
}
cout<<"stack size is: "<<st.size()<<endl; //size function
cout<<"popping...\n";
cout<<"stack elements are:\n";
while(!st.empty()){//stack not empty
cout<<"top element is:"<<st.top()<<endl;//print top element
st.pop();
count++;
}
if(st.empty())
cout<<"stack empty\n";
cout<<"stack size is: "<<st.size()<<endl; //size function
cout<<count<<" pop operation performed total to make stack empty\n";
return 0;
}
Output
输出量
...STACK STL...
enter 0 to stop pushing else enter any other integer
3
7
8
12
-4
0
stack size is: 5
...popping
stack elements are:
top element is:-4
top element is:12
top element is:8
top element is:7
top element is:3
stack empty
stack size is: 0
5 pop operation performed total to make stack empty
stl标准模板库