template<class T> class Queue{
friend ostream& operator<< <T> (ostream&, const Queue<T>&);
public:
Queue(int maxcount = 10):head(0),tail(0), count(maxcount)
{
data = new T[count]();
}
Queue(const Queue& rhs):head(rhs.head), tail(rhs.tail), count(rhs.count)
{
data = new T[count]();
memcpy(data, rhs.data, sizeof(T)*count);
}
Queue& operator=(const Queue& rhs)
{
if (this == &rhs)
{
return *this;
}
head = rhs.head;
tail = rhs.tail;
count = rhs.count;
delete []data;
data = new T[count]();
memcpy(data, rhs.data, sizeof(T)*count);
return *this;
}
~Queue()
{
delete []data;
}
T& Front() const;
void Push(const T&);
void Pop();
size_t Size() const;
inline bool Empty() const;
inline bool Full() const;
private:
int head;
int tail;
int count;
T* data;
};
template<class T> T& Queue<T>::Front() const
{
if (Empty())
{
exit(1);
}
return data[head];
}
template<class T> void Queue<T>::Push(const T& val)
{
if (!Full())
{
data[tail] = val;
tail = (tail+1)%count;
}
}
template<class T> void Queue<T>::Pop()
{
if (!Empty())
{
head = (head+1)%count;
}
}
template<class T> size_t Queue<T>::Size() const
{
return (tail-head+count)%count;
}
template<class T> bool Queue<T>::Empty() const
{
return head == tail;
}
template<class T> bool Queue<T>::Full() const
{
return (tail+1)%count == head;
}
template<class T> ostream& operator<<(ostream& os, const Queue<T>& q)
{
if (!q.Empty())
{
for (int i = q.head; i != q.tail; i = (i+1)%q.count)
{
os<<q.data[i]<<' ';
}
}
return os;
}
队列(数组形式)实现_c++
最新推荐文章于 2022-04-27 09:50:27 发布