实现C++ Stack(顺序栈)

参考QStack,继承自Vector

类声明

cpp 复制代码
template<typename T>
	class Stack :protected Vector<T>
	{
	public:
		explicit Stack()noexcept;
		Stack(const Stack&t)noexcept;
		Stack(Stack&&t)noexcept;

		Stack& operator= (const Stack& t)noexcept;
		Stack& operator= (Stack&& t)noexcept;

		~Stack();
		
		bool isEmpty()const noexcept;
		uint size()const noexcept;
		const T& top()const;
		T& top();
		Stack& push(const T& t)noexcept;
		T pop();
		void clear()noexcept;

		T& operator[](uint pos);
	private:
		int m_top;
	};

类实现

cpp 复制代码
template<typename T>
	MContainer::Stack<T>::Stack() noexcept
		:Vector<T>(10)
	{
		m_top = m_npos;
	}

	template<typename T>
	MContainer::Stack<T>::Stack(const Stack&t) noexcept
		:Vector<T>(t)
	{
		m_top = t.m_top;

	}

	template<typename T>
	MContainer::Stack<T>::Stack(Stack&&t) noexcept
		:Vector<T>(t)
	{
		m_top = t.m_top;

	}

	template<typename T>
	Stack<T>& MContainer::Stack<T>::operator=(const Stack& t) noexcept
	{
		if (this == &t)
			return *this;
		Vector<T>operator=(t);
		m_top = t.m_top;

	}

	template<typename T>
	Stack<T>& MContainer::Stack<T>::operator=(Stack&& t) noexcept
	{
		if (this == &t)
			return *this;
		Vector<T>operator=(std::move(t));
		m_top = t.m_top;
	}

	template<typename T>
	MContainer::Stack<T>::~Stack()
	{
		
	}

	template<typename T>
	inline bool Stack<T>::isEmpty() const noexcept
	{
		return m_top == m_npos;
	}

	template<typename T>
	uint MContainer::Stack<T>::size() const noexcept
	{
		return m_top;
	}

	template<typename T>
	const T& MContainer::Stack<T>::top() const
	{
		return last();
	}

	template<typename T>
	T& MContainer::Stack<T>::top()
	{
		return last();
	}

	template<typename T>
	Stack<T>& MContainer::Stack<T>::push(const T& t) noexcept
	{
		append(t);
		m_top++;
		return *this;
	}

	template<typename T>
	T MContainer::Stack<T>::pop()
	{
		T t = last();
		removeAt(m_top);
		m_top--;
		return t;
	}

	template<typename T>
	inline void Stack<T>::clear() noexcept
	{
		Vector<T>::clear();
		m_top = m_npos;
	}

	template<typename T>
	T& MContainer::Stack<T>::operator[](uint pos)
	{
		return Vector<T>::operator[](pos);
	}

为学习数据结构编写,容器可能存在问题。有建议可以留言指出,谢谢。

GitHub

相关推荐
一起努力啊~1 分钟前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
小北方城市网6 分钟前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
好易学·数据结构18 分钟前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
bkspiderx31 分钟前
C++中的map容器:键值对的有序管理与高效检索
开发语言·c++·stl·map
Hard but lovely32 分钟前
Linux: 线程同步-- 基于条件变量 &&生产消费模型
linux·开发语言·c++
独自破碎E44 分钟前
【归并】单链表的排序
数据结构·链表
L_09071 小时前
【C++】高阶数据结构 -- 平衡二叉树(AVLTree)
数据结构·c++
今儿敲了吗1 小时前
C++概述
c++·笔记
冰冰菜的扣jio1 小时前
Redis基础数据结构
数据结构·数据库·redis
C+-C资深大佬1 小时前
C++逻辑运算
开发语言·c++·算法