C++STL模板库适配器之stack容器

适配器

一丶适配器简介

Stl中的适配器,有栈 (stack) 队列 queue 根priority_queue
适配器都是包装了 vector list deque等顺序容器. 也可以看做是由这些容器实现的一个新的容器.
适配器没有提供迭代器.也不能同事插入或者删除多个元素.

二丶栈(stack)用法

1.栈的常用方法

  • push(x) 将元素入栈
  • pop() 弹出栈顶元素.只是弹出.没有返回值
  • top() 获取栈顶元素(不弹出)
  • empty() 判断栈是否为空, 为空返回true 不为空返回0
  • size() 返回栈中元素个数.

2.栈操作代码

使用适配器 stack 需要包含头文件

#include "stdafx.h"
#include <string>
#include <STACK>
#include <VECTOR>
#include <iostream>
using namespace std;


int main(int argc, char* argv[])
{
	stack<int> s; //如果使用int 底层默认使用deque容器
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);    //栈是先入后出的结构.所以栈中数据排列是 5 4 3 2 1 

	int nValue = s.top();	//获取栈顶元素
	s.pop();				//弹出栈顶元素.此时就没有5了
	cout << "栈顶元素为: " << nValue << endl;
	int nSize = s.size();		
	cout << "当前栈大小为: " << nSize << endl;


	//遍历栈
	while (!s.empty())
	{

		cout << s.top() << " " ;
		s.pop();
	}
	cout << endl;


	return 0;
}
原文地址:https://www.cnblogs.com/iBinary/p/9954398.html