STL --> stack栈

stack栈

   c++stack(堆栈)是一个容器的改编,它实现了一个先进后出的数据结构(FILO),使用该容器时需要包含#include<stack>头文件;

 

数据结构stack

定义stack对象示例:

stack<int>s1;
stack<string>s2;

 

stack的基本操作:

     s.empty()               如果栈为空返回true,否则返回false  
     s.size()                返回栈中元素的个数  
     s.pop()                 删除栈顶元素但不返回其值  
     s.top()                 返回栈顶的元素,但不删除该元素  
     s.push()                在栈顶压入新元素  

 

stack的使用范例:

 //栈 stack支持 empty() size() top() push() pop()
 // by MoreWindows(http://blog.csdn.net/MoreWindows)
 #include <stack>
 #include <vector>
 #include <list>
 #include <cstdio>
 using namespace std;
 int main()
 {
     //可以使用list或vector作为栈的容器,默认是使用deque的。
     stack<int, list<int>>      a;
     stack<int, vector<int>>   b;
     int i;
     
     //压入数据
     for (i = 0; i < 10; i++)
     {
         a.push(i);
         b.push(i);
     }
 
     //栈的大小
     printf("%d %d\n", a.size(), b.size());
 
     //取栈项数据并将数据弹出栈
     while (!a.empty())
     {
         printf("%d ", a.top());
         a.pop();
     }
     putchar('\n');
 
     while (!b.empty())
     {
         printf("%d ", b.top());
         b.pop();
     }
     putchar('\n');
     return 0;
 }

 

posted @ 2015-06-04 21:04  蚂蚁吃大象、  阅读(190)  评论(0)    收藏  举报