自编队列类,多个参数降低复杂度提高内存利用率。代码如下:
//-------------头文件----------------
#pragma once
using Type = int;
class CQueue
{
Type*m_pQueue;//容器体
int m_pTop,m_pBottom;//position bottom入top出
int m_nSize;//容器大小
int m_nCount;//个数------多出的参数
public:
CQueue(int nSize = 16);
~CQueue();
void Push(const Type& data );
void Pop();
Type& Front();
Type& Back();
int Size() { return m_nSize; }
bool IsEmpty() { return !m_nCount; }
};
//-------------实现文件--------------------------------------------
#include "CQueue.h"
#include<memory>
CQueue::CQueue(int nSize)
{
m_pQueue = new Type[m_nSize =nSize];
m_pTop= m_pBottom= 0;
m_nCount = 0;
}
~CQueue::CQueue()
{
delete m_pQueue ;
}
void CQueue::Push(const Type & data)
{
//确定尾部back的位置,并且没有满。
if (m_nCount<m_nSize) {
memcpy(&m_pQueue[m_pBottom ] ,&data,sizeof(Type));
++m_nCount;
m_pBottom = (m_pBottom + 1) % m_nSize;
}
}
void CQueue::Pop()
{
if (m_nCount) {
m_pTop = (m_pTop + 1) % m_nSize;
--m_nCount;
}
}
Type & CQueue::Front()
{
return m_pQueue[m_pTop];
}
Type & CQueue::Back()
{
return m_pQueue[m_pBottom];
}