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

相关推荐
saltymilk14 小时前
使用 C++ 模拟 ShaderLanguage 的 swizzle
c++·模板元编程
xlp666hub20 小时前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
得物技术21 小时前
搜索 C++ 引擎回归能力建设:从自测到工程化准出|得物技术
c++·后端·测试
哈里谢顿2 天前
跳表(Skip List):简单高效的有序数据结构
数据结构
xlp666hub2 天前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
会员源码网2 天前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
xlp666hub2 天前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
不想写代码的星星2 天前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub3 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
任沫3 天前
字符串
数据结构·后端