实现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

相关推荐
计算机安禾44 分钟前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio
kpl_201 小时前
智能指针(C++)
c++·c++11·智能指针
Darkwanderor2 小时前
高精度计算——基础模板整理
c++·算法·高精度计算
Tanecious.3 小时前
蓝桥杯备赛:Day5-P1036 选数
c++·蓝桥杯
mmz12073 小时前
深度优先搜索DFS(c++)
c++·算法·深度优先
汀、人工智能4 小时前
[特殊字符] 第103课:单词搜索II
数据结构·算法·均值算法·前缀树·trie·单词搜索ii
憧憬从前4 小时前
算法学习记录DAY1
c++·学习
来自远方的老作者4 小时前
第7章 运算符-7.2 赋值运算符
开发语言·数据结构·python·赋值运算符
A.A呐4 小时前
【C++第二十四章】异常
开发语言·c++
wanderist.4 小时前
算法模板-字符串
数据结构·算法·哈希算法