C++ STACK 入门

转自  北齐风凉 的博客

http://my.oschina.net/Tsybius2014/blog/293618

1.Stack类学习

1)建立stack<string>

2)调用push函数将数据压入栈中

3)调用size函数查看当前栈内元素数量

4)调用empty函数检测栈是否为空

5)如果不为空则不断调用pop函数将元素从栈中取出(后入先出)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stack>
 
using  namespace  std;
 
int  main()
{
     stack<string> stkNameList;
 
     stkNameList.push( "Tsybius" ); 
     cout <<  "Push: "  << stkNameList.top() << endl;
     stkNameList.push( "Galatea" );
     cout <<  "Push: "  << stkNameList.top() << endl;
 
     cout <<  "Stack size: "  << stkNameList.size() << endl;
 
     while (!stkNameList.empty())
     {
         cout <<  "Pop: "  << stkNameList.top()  << endl;
         stkNameList.pop();
     }
 
     return  0;
}

运行结果

2.Queue类学习

1)建立queue<string>

2)调用push函数将元素加入queue

3)调用size函数查看队列内元素数量

4)调用front和back函数查看队列首位元素

5)调用empty函数查看队列是否为空

6)如果队列不为空则调用pop函数将元素从队列中取出(先入先出)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <queue>
 
using  namespace  std;
 
int  main()
{
     queue<string> queNameList;
 
     queNameList.push( "Tsybius" );
     cout <<  "Push: Tsybius"  << endl;
     queNameList.push( "Galatea" );
     cout <<  "Push: Galatea"  << endl;
     queNameList.push( "Gnaeus" );
     cout <<  "Push: Gnaeus"  << endl;
 
     cout <<  "Queue Size: "  << queNameList.size() << endl;
     cout <<  "Front: "  << queNameList.front() << endl;
     cout <<  "Back: "  << queNameList.back() << endl;
 
     while (!queNameList.empty())
     {
         cout <<  "Pop: "  << queNameList.front() << endl;
         queNameList.pop();
     }
 
     return  0;
}

运行结果

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值