手机
当前位置:查字典教程网 >编程开发 >C语言 >C++中用两个标准容器stack,实现一个队列的方法详解
C++中用两个标准容器stack,实现一个队列的方法详解
摘要:代码如下所示:复制代码代码如下://StackToQueue.cpp:定义控制台应用程序的入口点。//用两个标准容器stack,实现一个队列...

代码如下所示:

复制代码 代码如下:

// StackToQueue.cpp : 定义控制台应用程序的入口点。

//用两个标准容器stack,实现一个队列

#include "stdafx.h"

#include <iostream>

#include <stack>

using namespace std;

template <class T>

class StackToQueue

{

public:

StackToQueue()

{

stack1;

stack2;

}

void push(T e)

{

while (!stack2.empty())

{

T temp;

temp = stack2.top();

stack2.pop();

stack1.push(temp);

}

stack2.push(e);

while (!stack1.empty())

{

T temp;

temp = stack1.top();

stack1.pop();

stack2.push(temp);

}

}

void pop()

{

stack2.pop();

}

T front()

{

if (!empty())

{

return stack2.top();

}

else

{

return NULL;

}

}

bool empty()

{

return stack2.empty();

}

size_t size()

{

return stack2.size();

}

private:

stack<T> stack1, stack2;

};

int _tmain(int argc, _TCHAR* argv[])

{

StackToQueue<int> queue;

int i(0);

cout << "Enter several integer number,and press ctrl+z to the end." << endl;

while (cin >> i)

{

queue.push(i);

}

cout << "The front element is: " << queue.front() << endl;

cout << "The size now is: " << queue.size() << endl;

if (!queue.empty())

{

cout << "Pop one element now." << endl;

queue.pop();

}

cout << "The front element is: " << queue.front() << endl;

cout << "The size now is: " << queue.size() << endl;

return 0;

}

【C++中用两个标准容器stack,实现一个队列的方法详解】相关文章:

C++中的操作符重载详细解析

C++读写Excel的实现方法详解

C语言中的内联函数(inline)与宏定义(#define)详细解析

C/C++中可变参数的用法详细解析

基于atoi()与itoa()函数的内部实现方法详解

C++多态的实现及原理详细解析

让应用程序只运行一个实例的实现方法

STl中的排序算法详细解析

深入分析C语言中结构体指针的定义与引用详解

使用C++实现全排列算法的方法详解

精品推荐
分类导航