C++类模板实现队列(动态数组实现)

  1. 使用动态数组保存数据
  2. 队列满自动扩充容量
  • 头文件如下
#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++;
	//std::cout << " m_rear: " << m_rear << std::endl;
	
}

template<class T>
inline void MyQueue<T>::Pop()
{
	if (m_size == 0)
	{
		throw "空队列";
	}
	else
	{
		//std::cout << " front: " << m_front << std::endl;
		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();

	}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值