队列的数组实现

/*
 * queue_2.cpp
 *
 *  Created on: 2013年8月2日
 *      Author: 黄东东
 *      为了能有章泽天这样的女朋友而不断努力。。。。。
 *      fighting。。。。。。。
 */

#include <iostream>
typedef int T;
using namespace std;

class Queue {
	int a[5];
	int b;//队首元素
	int n;//有效元素个数

public:
	Queue() :
			b(0), n(0) {

	}
	Queue& push(const T& d) {

		if (full()) {
			throw "满";
		}
		a[(b + n++) % 5] = d;

		return *this;
	}

	T pop() {

		if (empty()) {
			throw "空";
		}
		--n;
		return a[b++ % 5];
	}

	const T& front() {

		return a[b % 5];
	}

	const T& back() {

		return a[(b + n - 1) % 5];
	}

	bool empty() {

		return n == 0;
	}

	bool full() {

		return n == 5;
	}

	int size() {

		return n;
	}

	void clear() {

		b = 0;
		n = 0;
	}

};
int main() {
	Queue q;
	try {
		q.push(1).push(2).push(3).push(4).push(5);

		cout << q.pop() << endl;
		cout << q.pop() << endl;

		q.push(6).push(7).push(8);
	} catch (const char* e) {

		cout << "异常:" << e << endl;
	}

	while (!q.empty()) {
		cout << q.pop() << endl;
	}

}


原文地址:https://www.cnblogs.com/riskyer/p/3233907.html