C++ STACK 入门

来源:互联网 发布:淘宝onlyanna 罗晓颖 编辑:程序博客网 时间:2024/05/20 09:24

转自  北齐风凉 的博客

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

0 0