【STL详解】stack


前言

本篇文章将总结SLT - stack,以及其常用方法。

一、STL?

STL 是“Standard Template Library”的缩写,中文译为“标准模板库”。STL 是 C++ 标准库的一部分。
常用的容器:vector,stack,queue,deque,list,map,set。
头文件:algorithm,stack。
以下将展开讲解容器 stack的用法.

二、stack

1. stack的创建

#include<iostream>
#include<algorithm>
#include<stack>

using namespace std;

int main() {
	stack<int> st;
	stack<int> st(1,2,3,5);
	return 0;
}

2. stack相关方法

int size = st.size();
int topNum = st.top();//栈顶元素

st.push(a);//元素入栈
st.pop();//元素出栈
st.empty();//判断是否为空

3. 如何对satck进行排序

在vector中,可以使用sort函数排序,那么stack怎么进行排序呢?(vector详解:vector

/*
从小到大的排序,利用辅助栈,每次取出一个元素,将r中更大的数,移回s中,直到r之前的元素是比r更小(=)或者是r空
*/
stack<int> sort(stack<int> s)//s {3,4,2,6,1} 
{
	stack<int> r;//辅助栈
	while(!s.empty())
	{
		int temp = s.top();
		s.pop();
		while(!r.empty() && r.top()>temp)
		{
			s.push(r.top());
			r.pop();
		}
		r.push(temp);
	}
	return r;
}

`提示:代码手敲,欢迎指出错误,以及知识补充,下一期说:queue和deque


版权声明:本文为weixin_43595702原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。