stack的介绍使用及模拟实现

本文深入解析了栈数据结构的特性与应用,详细介绍了栈作为一种后进先出的容器适配器,其基本操作包括构造、判空、返回元素数量、获取栈顶元素、入栈和出栈。并通过实例演示了栈的使用方法,同时提供了基于deque的栈模拟实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stack的介绍使用及模拟实现

1、stack的介绍

1、stack是一种容器适配器,这种适配器的特点是后进先出
2、stack是作为容器适配器被实现的
3、stack的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类,支持判空、返回栈顶、入栈,出栈的操作
4、默认使用deque作为stack的底层

2、stack的基本操作

函数说明接口说明
stack()构造空的栈
empty()检测stack是否为空
size()返回stack中元素的个数
top()返回栈顶元素的引用
push()将元素val压入stack中
pop()将stack中尾部的元素弹出
#include <iostream>
#include <stack>

using namespace std;

void TestStack1()
{
	stack<int> s1;//构造s1
	stack<int> s2(s1);//拷贝构造s2
}

void TestStack2()
{
	stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);

	cout << s.empty() << endl;
	cout << s.size() << endl;
	cout << s.top() << endl;
	
	for (int i = 0; i < s.size(); i++)
	{
		cout << s.top() << endl;
		s.pop();
	}
}

int main()
{
	TestStack1();
	TestStack2();
	system("pause");
	return 0;
}

2、stack的模拟实现

stack.h

#include <iostream>
#include <deque>

using namespace std;

namespace gwp
{
	template<class T, class Con = deque<T>>
	class stack
	{
	public:
		stack()
		{

		}

		void push(const T& x)
		{
			m_c.push_back(x);
		}

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

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

		const T& top() const
		{
			return m_c.back();
		}

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

		bool empty()
		{
			return m_c.empty();
		}
		
	private:
		Con m_c;
	};
}

stack.cpp

#include <iostream>
#include "stack.h"

using namespace std;

int main()
{
	gwp::stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	
	cout << s.size() << endl;
	cout << s.empty() << endl;
	cout << s.top() << endl;

	s.pop();

	cout << s.top() << endl;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值