基本操作:
push(x) 将x加入栈中,即入栈操作
pop() 出栈操作(删除栈顶),只是出栈,没有返回值
top() 返回第一个元素(栈顶元素)
size() 返回栈中的元素个数
empty() 当栈为空时,返回 true
使用方法:
和队列差不多,其中头文件为:
#include <stack>
定义方法为:
stack<int>s1;//入栈元素为 int 型
stack<string>s2;// 入队元素为string型
stack<node>s3;//入队元素为自定义型
stack<string>s2;// 入队元素为string型
stack<node>s3;//入队元素为自定义型
程序示例:
01 | #include <iostream> |
02 | #include <stack> |
03 | using namespace std; |
04 | int main() |
05 | { |
06 | stack< int > STACK; |
07 | STACK.push(5); |
08 | STACK.push(6); |
09 | STACK.push(7); |
10 | STACK.pop(); |
11 | cout<<STACK.top()<<endl; |
12 | cout<<STACK.size()<<endl; |
13 | cout<<STACK.empty()<<endl; |
14 | return 0; |
15 | } |
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;
int main()
{
/* stack<int> S;
S.push(5);
S.push(6);
S.push(7);
S.pop();
S.pop();
printf("%d\n", S.top());
S.pop();
printf("%d\n", S.size());
printf("%d", S.empty());
*/
queue<int> Q;
Q.push(5);
Q.push(4);
Q.push(3);
Q.pop();
printf("%d\n", Q.back());
Q.pop();
printf("%d\n", Q.size());
printf("%d\n", Q.empty());
printf("%d\n", Q.front());
Q.pop();
printf("%d\n", Q.empty());
return 0;
}
原创文章,转载请注明: 转载自C/C++程序员之家
本文链接地址: STL中栈的使用