- 使用动态数组保存数据
- 队列满自动扩充容量
#pragma once
template <class T>
class MyQueue
{
public:
MyQueue(size_t n = 10);
~MyQueue();
void Push(const T&);
void Pop();
T& Front() const;
T& Rear() const;
bool IsEmpty() const;
size_t Size() const;
private:
size_t m_capacity;
size_t m_size;
int m_front;
int m_rear;
T* m_ptrQueue;
void __ExpanCapacity();
};
template<class T>
inline MyQueue<T>::MyQueue(size_t n) : m_capacity(n), m_size(0)
{
m_front = m_rear = 0;
if (n < 1)
{
throw "参数错误,容量必须大于1";
}
m_ptrQueue = new T[n];
if (m_ptrQueue == nullptr)
{
throw "系统错误,内存申请失败";
}
}
template<class T>
inline MyQueue<T>::~MyQueue()
{
if (m_ptrQueue != nullptr)
delete[] m_ptrQueue;
}
template<class T>
inline void MyQueue<T>::Push(const T& item)
{
if (m_size == m_capacity)
{
__ExpanCapacity();
}
m_rear = (m_rear + 1) % m_capacity;
m_ptrQueue[m_rear] = item;
m_size++;
}
template<class T>
inline void MyQueue<T>::Pop()
{
if (m_size == 0)
{
throw "空队列";
}
else
{
m_front = (m_front + 1) % m_capacity;
m_ptrQueue[m_front].~T();
m_size--;
}
}
template<class T>
inline T& MyQueue<T>::Front() const
{
if (m_size == 0)
{
throw "空队列";
}
else
{
return m_ptrQueue[(m_front + 1) % m_capacity];
}
}
template<class T>
inline T& MyQueue<T>::Rear() const
{
if (m_size == 0)
{
throw "空队列";
}
else
{
return m_ptrQueue[m_rear];
}
}
template<class T>
inline bool MyQueue<T>::IsEmpty() const
{
return m_size == 0;
}
template<class T>
inline size_t MyQueue<T>::Size() const
{
return m_size;
}
template<class T>
inline void MyQueue<T>::__ExpanCapacity()
{
T* temp = new T[2 * m_capacity];
if (m_front == m_capacity - 1)
{
std::copy(m_ptrQueue, m_ptrQueue + m_capacity, temp);
}
else
{
std::copy(m_ptrQueue + m_front + 1, m_ptrQueue + m_capacity, temp);
std::copy(m_ptrQueue, m_ptrQueue + m_front + 1, temp + m_capacity - m_front - 1);
}
m_rear = m_capacity - 1;
m_capacity *= 2;
m_front = m_capacity - 1;
delete[] m_ptrQueue;
m_ptrQueue = temp;
}
MyQueue<int> queue;
for (size_t i = 0; i < 21; i++)
{
queue.Push(i);
}
while (!queue.IsEmpty())
{
cout << queue.Front() << " size:" << queue.Size() << endl;
queue.Pop();
}
for (size_t i = 0; i < 11; i++)
{
queue.Push(i*10 + 1);
}
while (!queue.IsEmpty())
{
cout << queue.Front() << " size:" << queue.Size() << endl;
queue.Pop();
}