『C++primer』チーターネット校テンプレートと汎用プログラミング2018/10/9
2704 ワード
2.C++の汎用キュー
3.シーケンスキュー
4.チェーンキュー
キュー-シーケンスキュー-システムソフトウェア開発、システムのスレッドプール
先先先出(FIFO)または後進後出(LILO)
キャプテン
キューの操作、push pop,b
#include
#include " .h"
#include
using namespace std;
int main()
{
cout < q(5);
q.Push('A');
q.Push('B');
q.Push('C');
cout <
#ifndef _ _H
#define _ _H
#include
template
class Queue
{
public:
Queue(int queueCapacity = 10); // , 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;
};
// , ,capacity
template
Queue::Queue(int queueCapacity):capacity(queueCapacity)
{
if(capacity < 1) throw "Queue capacity must be >0";
queue = new T[capacity];
front = rear = 0;
}
template
inline bool Queue::IsEmpty() const
{
return front == rear; //
}
template
void Queue::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;
delete[] queue;
queue = newQueue;
}
rear = (rear+1)%capacity; //
queue[rear] = item;
}
template
inline T& Queue::Front() const
{
if(IsEmpty()) throw "Queue is empty ,No Front element";
return queue[(front +1) %capacity];
}
template
inline T& Queue ::Rear() const
{
if(IsEmpty()) throw "Queue is empty ,no rear element";
return queue[rear];
}
template
void Queue::Pop()
{
if(IsEmpty()) throw "Queue is empty .Canot delete.";
front = (front+1) %capacity;
queue[front].~T();
}
#endif // _