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

相关推荐
Jiu-yuan17 小时前
C++文件操作
c++
VT.馒头17 小时前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript
2301_7634725817 小时前
实时系统下的C++编程
开发语言·c++·算法
im_AMBER17 小时前
Leetcode 113 合并 K 个升序链表
数据结构·学习·算法·leetcode·链表
阿猿收手吧!17 小时前
【C++】深入理解C++ Atomic内存序:解决什么问题?怎么用?
开发语言·c++
小黄人软件17 小时前
【MFC】底层类显示消息到多个界面上。 MFC + 线程 + 回调 的标准模板 C++函数指针
c++·mfc
兩尛17 小时前
c++遍历容器(vector、list、set、map
开发语言·c++
2301_7903009617 小时前
C++与Docker集成开发
开发语言·c++·算法
AutumnorLiuu17 小时前
C++并发编程学习(二)—— 线程所有权和管控
java·c++·学习
一切尽在,你来17 小时前
C++ 零基础教程 - 第 5 讲 变量和数据类型
开发语言·c++