c++之队列的数组实现与STL示例

栈是一种特殊的线性表
线性表是具有想同类型的n(n>=0)个数据元素组成的有序有限序列

队列的数组实现
ArrayQueue.h

#include<iostream>
using namespace std;

template<class T>
class ArrayQueue
{
public:
	ArrayQueue();
	~ArrayQueue();
	void add(T data);
	T front();
	T pop();
	int size();
	bool IsEmpty();
private:
	T *arr;
	int count;
};

template<class T>
ArrayQueue<T>::ArrayQueue()
{
	arr = new T[12];
	if (!arr)
		cout << "arr malloc error!" << endl;
}

template<class T>
ArrayQueue<T>::~ArrayQueue()
{
	if (arr)
	{
		delete[] arr;
		arr = NULL;
	}
}

template<class T>
void ArrayQueue<T>::add(T data)
{
	arr[count++] = data;
}

template<class T>
T ArrayQueue<T>::front()
{
	return arr[0];
}

template<class T>
T ArrayQueue<T>::pop()
{
	int i = 0;
	T ret = arr[0];
	count--;
	while (i++ < count)
		arr[i - 1] = arr[i];
	return ret;
}

template<class T>
int ArrayQueue<T>::size()
{
	return count;
}

template<class T>
bool ArrayQueue<T>::IsEmpty()
{
	return !count;
}

main.cpp

#include"ArrayQueue.h"

using namespace std;

int main()
{
	int tmp = 0;
	ArrayQueue<int> *aqueue = new ArrayQueue<int>();

	aqueue->add(10);
	aqueue->add(20);
	aqueue->add(30);

	tmp = aqueue->pop();
	cout << "tmp=" << tmp << endl;

	tmp = aqueue->front();
	cout << "tmp=" << tmp << endl;

	aqueue->add(40);
	cout << "IsEmpty=" << aqueue->IsEmpty() << endl;
	cout << "size=" << aqueue->size() << endl;

	while (!aqueue->IsEmpty())
	{
		tmp = aqueue->pop();
		cout << tmp << endl;
	}

	system("pause");
	return 0;
}

STL示例

#include<iostream>
#include<queue>
using namespace std;

int main()
{
	int tmp=0;
	queue<int> iqueue;

	iqueue.push(10);
	iqueue.push(20);
	iqueue.push(30);

	iqueue.pop();

	tmp = iqueue.front();
	cout << "tmp=" << tmp << endl;

	iqueue.push(40);

	cout << "empty=" << iqueue.empty() << endl;
	cout << "size=" << iqueue.size() << endl;

	while (!iqueue.empty())
	{
		tmp = iqueue.front();
		cout << tmp << ' ';
		iqueue.pop();
	}

	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值