使用数组实现队列

本文介绍了一个使用C++模板实现的固定大小队列类。该队列类支持基本的队列操作,如入队(push)、出队(pop)、获取队首元素(front)等,并通过模板使其实现类型泛化,可用于多种数据类型。文章提供了完整的类定义及一个简单的测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdlib>
#include <cassert>

using namespace std;

template<class T> 
class queue {
public:
	typedef std::size_t size_type;
	typedef T value_type;
	static const size_type CAPACITY = 30;
	queue() {
		used = 0;
		first = 0;
		last = CAPACITY-1;
	}
	void push(const value_type& entry) {
		assert(size() < CAPACITY);
		last = next_index(last);
		data[last] = entry;
		used++;
	}
	void pop() {
		assert(!empty());
		first = next_index(first);
		used--;	
	}
	value_type front() {
		assert(!empty());
		return data[first];
		
	}
	bool empty() { return (used ==0); }
	size_type size() { return used; }
private:
	value_type data[CAPACITY];
	size_type used;
	size_type first;
	size_type last;
	size_type next_index(size_type i) const {
		return (i+1)%CAPACITY;
	}
};

int main() {
	queue<int> ique;
	for(int i = 0; i < 5; i++)
		ique.push(i);
	cout << "The size of the queue is: " << ique.size() << endl;
	while(!ique.empty()) {
		cout << ique.front() << endl;
		ique.pop();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值