欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【基本数据结构】(循环)队列/queue/FIFO

程序员文章站 2022-03-14 15:06:51
...

类模板

#pragma once
#include <iostream>
#include <cassert>

template <typename Type, int MAXSIZE>
class queue//FIFO context
{
	//Elements are pushed into the "back_" of the specific container
	//and popped from its "front_".
private:
	Type* info;
	int front_, back_;//Emements from (front_ + 1) to back_;
	int count;
public:
	queue(){
		info = new Type[MAXSIZE];
		front_ = 0;	back_ = 0;
		count = 0;
	}
	~queue(){
		delete[] info;
	}
	bool empty(){
		return !count;
	}
	int size(){
		return count;
	}
	Type front(){
		assert(count);
		return info[(front_ + 1) % MAXSIZE];
	}
	Type back(){
		assert(count);
		return info[back_];
	}
	void push_back(Type ins){
		assert(count < MAXSIZE);
		count++;
		back_ = (back_ + 1) % MAXSIZE;
		info[back_] = ins;
		
	}
	void pop_front(){
		assert(count);
		front_ = (front_ + 1) % MAXSIZE;
		count--;
	}
};

ACM简单实现

const int MAXSIZE = 10;
int info[MAXSIZE], l = 0, r = 0, ele = 0;//Elements from (l + 1) to r;
inline int putin(int ins) {
	ele++;
	r = (r + 1) % MAXSIZE;
	info[r] = ins;
}
inline int pop() { l = (l + 1) % MAXSIZE; }

STL实现

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

int main()
{
	queue<char> arr;
	arr.push('c');
	arr.push('a');
	cout << arr.empty() << endl;
	cout << arr.front() << endl;
	cout << arr.back() << endl;
	arr.pop();
	arr.push('s');
	cout << arr.empty() << endl;
	cout << arr.front() << endl;
	cout << arr.back() << endl;
	return 0;
}
相关标签: FIFO 队列 queue