C++ stack和queue 模拟实现

stack和queue 模拟实现

      • 模拟栈实现
      • 模拟队实现

模拟栈实现

1 栈是一种容器适配器,专门设计用于后进先出的后进先出环境,在这种环境中,元素只从容器的一端插入和提取。
2 栈是作为容器适配器实现的,这些适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素从特定容器的“后面”(即堆栈的顶部)被推入/弹出。
3 底层容器可以是任何标准容器类模板或其他特定设计的容器类。集装箱应支持以下操作:

  • empty
  • size
  • back
  • push_back
  • pop_back
//头文件
#include <list>
#include <vector>
#include <deque>

namespace test
{
	template<class T,class Container = deque<T>>
	class stack
	{
	public:
		void push(const T& x)
		{
			_con.push_back(x);
		}

		void pop()
		{
			_con.pop_back();
		}

		T& top()
		{
			return _con.back();
		}

		size_t size()
		{
			return _con.size();
		}

		bool empty()
		{
			return _con.empty();
		}

	private:
		Container _con;
	};

	void test_stack()
	{
		stack<int> st1;
		st1.push(1);
		st1.push(2);
		st1.push(3);
		st1.push(4);

		while (!st1.empty())
		{
			cout << st1.top() << " ";
			st1.pop();
		}
		cout << endl;
	}
}

C++ stack和queue 模拟实现_第1张图片

模拟队实现

1 先进先出队列队列是一种容器适配器,专门设计用于在FIFO上下文中操作(先进先出),其中将元素插入容器的一端并从另一端提取。
2 队列是作为容器适配器实现的,容器适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素被推入特定容器的“后面”,并从其“前面”弹出。
3 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类模板容器类。该底层容器应至少支持以下操作:

  • empty
  • size
  • front
  • back
  • push_back
  • pop_front
//头文件
#include <vector>
#include <list>
#include <deque>

namespace test
{
	template<class T, class Container = deque<T>>
	class queue
	{
	public:
		void push(const T& x)
		{
			_con.push_back(x);
		}
		
		void pop()
		{
			_con.pop_front();
			//_con.erase(_con.begin);
		}

		T& front()
		{
			return _con.front();
		}
		
		T& back()
		{
			return _con.back();
		}

		size_t size()
		{
			return _con.size();
		}

		bool empty()
		{
			return _con.empty();
		}
	private:
		Container _con;
	};
	void test_queue()
	{
		queue<int, list<int>> q;
		q.push(1);
		q.push(2);
		q.push(3);
		q.push(4);

		while (!q.empty())
		{
			cout << q.front() << " ";
			q.pop();
		}
		cout << endl;
	}
}

C++ stack和queue 模拟实现_第2张图片

你可能感兴趣的:(c++,c++,rpc,网络)