STL学习之stack

来源:互联网 发布:linux 开机启动服务器 编辑:程序博客网 时间:2024/05/17 07:52

栈是一种容器适配器,是一种后入先出(LIFO )队列。

基本操作

stack<int>s;构造

stack<int>s1(s2);将s2赋值给s1

s.push(x);入栈

s.pop();出栈,注意:出栈操作只是删除栈顶的元素,并不返回该元素

s.top();访问栈顶

s.empty().判断栈空,当栈空时返回true

s.size();栈中的元素个数


问题:用stack实现FIFO的功能


// FIFObuildinStack.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<stack>#include<iostream>using namespace std;class FIFO{private:stack<int>a;    stack<int>b;public://FIFO();void enqueue(int in);int dequeue();bool isempty();//~FIFO();};void FIFO::enqueue(int in)//入队{int k;while (!b.empty()){k = b.top();a.push(k);b.pop();}a.push(in);}int FIFO::dequeue()//出队{int cc;while (!a.empty()){cc = a.top();a.pop();b.push(cc);}int bb = b.top();b.pop();return bb;}bool FIFO::isempty(){return(a.empty() && b.empty());}int _tmain(int argc, _TCHAR* argv[]){FIFO fifo;fifo.enqueue(1);fifo.enqueue(3);fifo.enqueue(8);cout << fifo.dequeue() << endl;cout << fifo.dequeue() << endl;if (fifo.isempty())cout << "现在FIFO为空" << endl;cout << fifo.dequeue() << endl;if (fifo.isempty())cout << "现在FIFO为空" << endl;system("pause");return 0;}


0 0