【c++】【STL】stack详解

目录

stack类的作用

stack是stl库提供的一种容器适配器,也就是我们数据结构中学到的栈,是非常常用的数据结构,特点是遵循LIFO(last in first out,也就是后进先出)原则。

什么是容器适配器

stl中提供的类很多都叫容器,但有一些叫做容器适配器,容器适配器到底是啥呢?我们不妨先抛掉容器这两个字,先来谈谈适配器,适配器是软件设计之中的一种概念,即基于原有的接口设计适配出用户想要的接口,是一种设计模式,适配器这种设计模式提升了代码复用性以及系统扩展性,降低了代码的耦合度,是一种优秀的设计模式。那么对于容器适配器来说,就是利用已有的容器进行各种操作封装出新的类,这就叫容器适配器。

stack的接口

构造函数

cpp 复制代码
explicit stack (const container_type& ctnr = container_type());

一般来说不用给参数,直接调用默认构造就行。

empty

cpp 复制代码
bool empty() const;

栈的判空。

size

cpp 复制代码
size_type size() const;

返回栈的元素数。

top

cpp 复制代码
      value_type& top();
const value_type& top() const;

返回栈顶元素。

push

cpp 复制代码
void push (const value_type& val);

入栈。

pop

cpp 复制代码
void pop();

出栈。

swap

cpp 复制代码
void swap (stack& x) noexcept(/*see below*/);

栈自己的交换函数。

关系运算符重载

cpp 复制代码
template <class T, class Container>
  bool operator== (const stack<T,Container>& lhs, const stack<T,Container>& rhs);
template <class T, class Container>
  bool operator!= (const stack<T,Container>& lhs, const stack<T,Container>& rhs);
template <class T, class Container>
  bool operator<  (const stack<T,Container>& lhs, const stack<T,Container>& rhs);
template <class T, class Container>
  bool operator<= (const stack<T,Container>& lhs, const stack<T,Container>& rhs);
template <class T, class Container>
  bool operator>  (const stack<T,Container>& lhs, const stack<T,Container>& rhs);
template <class T, class Container>
  bool operator>= (const stack<T,Container>& lhs, const stack<T,Container>& rhs);

stack类的实现

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>

#include<deque>

using namespace std;

namespace jiunian
{
	template<class T, class container = deque<T>>
	class stack
	{
	public:
		typedef stack<T, container> Self;

		//stack()
		//{
		//}

		//stack(Self& x):
		//	con(x.con)
		//{
		//}

		//~stack()
		//{
		//}

		bool empty()const
		{
			return con.empty();
		}

		size_t size()const
		{
			return con.size();
		}

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

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

		void push(const T& val)
		{
			con.push_back(val);
		}

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

		void swap(Self& x)
		{
			con.swap(x.con);
		}

		Self operator=(Self x)
		{
			con = x.con;
			return *this;
		}
	private:
		container con;
	};
}

stack作为一个容器适配器,实现起来相比其他容器明显简单了不少,因为其作为容器适配器只需要对其他容器的接口进行封装就行,不需要自己造轮子。实现过程一看就懂,不做过多赘述。

相关推荐
m0_380743877 分钟前
给 Claude API 调用补上超时重试和错误分类
开发语言·人工智能·php
Draw Stars16 分钟前
Git BASH安装教程
开发语言·git·bash
vortex524 分钟前
一文讲透 Zsh 与 Bash 的区别
开发语言·bash
千谦阙听28 分钟前
C++类和对象(中):默认成员函数、构造与析构、拷贝构造、运算符重载
开发语言·c++·学习
weixin_307779131 小时前
一维无粘 Burgers 方程的激波形成问题:MacCormack 格式求解
c++·算法·matlab
HugoStudio_SWAN1 小时前
洛谷 B4500 / B4449 / B3843 凯撒密码、密码强度与密码合规——加密与安全的三道门
c++·学习·程序人生·算法·安全
雾里看山2 小时前
源码目录、构建目录与 out-of-source build
c++·软件构建·cmake
渡我白衣4 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
天下无敌笨笨熊4 小时前
C#Modbus串口开发心得
开发语言·c#
电商API_180079052474 小时前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘