队列是很重要的数据结构,一般用来实现重要的系统软件开发,比如线程池,线程池的工作列表都是用队列实现的
队列先进先出(FIFO)或后进后出(LILO)
队首,队尾
队列的操作:
Push 入队
Pop 出对
Front 队首
Rear 队尾
IsEmpty 是否为空
队列有两种实现方法,一种是使用动态数组,一种是使用链表来实现。
今天使用动态数组来实现顺序队列。
在VS2013中新建空项目,添加头文件 顺序队列.h 添加源文件main.cpp
//顺序队列.h
#ifndef _顺序队列_H
#define _顺序队列_H
template<class T>
class Queue{
public:
Queue(int queueCapacity = 10);
bool IsEmpty() const;
T& Front() const;
T& Rear() const;
void Push(const T& item);
void Pop();
private:
T *queue;
int front;
int rear;
int capacity;
};
template<class T>
Queue<T>::Queue(int queueCapacity) :capacity(queueCapacity){
if (capacity < 1)throw "Queue capacity must be >0";
queue = new T[capacity];
front = rear = 0;
}
template<class T>
inline bool Queue<T>::IsEmpty() const{
return front == rear;
}
template<class T>
void Queue<T>::Push(const T & item){
/*if (rear == capacity - 1){
rear = 0;
}
else{
rear++;
}*/
if ((rear + 1) % capacity == front){
//队列满了,加倍
T* newQueue = new T[2 * capacity];
int start = (front + 1) % capacity;
if (start < 2){
copy(queue + start, queue + start + capacity - 1, newQueue);
}
else{
copy(queue + start, queue + capacity, newQueue);
copy(queue, queue + rear + 1, newQueue + capacity - start);
}
front = 2 * capacity - 1;
rear = capacity - 2;
capacity = 2 * capacity;
delete[]queue;
queue = newQueue;
}
rear = (rear + 1) % capacity;//高水平!
queue[rear] = item;
}
//队首的位置是空的,始终是空的,浪费了一个存储空间,但是加快了push和pop的速度
//Front()是队首
template<class T>
inline T& Queue<T>::Front() const{
if (IsEmpty())throw "Queue is empty. No front element";
return queue[(front + 1) % capacity];
}
//Rear()是队尾
template<class T>
inline T& Queue<T>::Rear() const{
if (IsEmpty()) throw "Queue is Empty, No rear element";
return queue[rear];
}
template<class T>
void Queue<T>::Pop(){
if (IsEmpty())throw "Queue is empty, Can not delete.";
front = (front + 1) % capacity;
queue[front].~T();
}
#endif
下面是主程序:
//main.h
#define _SCL_SECURE_NO_WARNINGS
#include<iostream>
#include "顺序队列.h"
using namespace std;
int main(){
cout << "测试顺序队列" << endl;
Queue<char> q(6);
q.Push('A');
q.Push('B');
q.Push('C');
cout << q.Front() << "," << q.Rear() << endl;
q.Push('D');
q.Push('E');
cout << q.Front() << "," << q.Rear() << endl;
/*q.Pop();
cout << q.Front() << "," << q.Rear() << endl;*/
q.Push('F');
cout << q.Front() << "," << q.Rear() << endl;
q.Push('G');
cout << q.Front() << "," << q.Rear() << endl;
system("pause");
return 0;
}
总结:这里学习了使用动态数组实现队列,这个队列当容量不够时会自动扩大队列容量。