C++stack模板类

本文介绍了C++中的Stack模板类,它是一个后入先出(LIFO)的数据结构,适用于容器适配器。Stack支持push、size、top等操作,并可以使用vector、deque等作为基础容器。通过实例展示了如何使用Stack进行元素的添加、删除和检查。
摘要由CSDN通过智能技术生成

stack 介绍

栈是一种容器适配器,特别为后入先出而设计的一种(LIFO ),那种数据被插入,然后再容器末端取出

栈实现了容器适配器,这是用了一个封装了的类作为他的特定容器,提供了一组成员函数去访问他的元素,元素从特定的容器,也就是堆栈的头取出袁术。

这个基础的容器可能是任何标准的容器类,和一些其他特殊设计的模板类,唯一的要求就是要支持一下的操作

[cpp]  view plain   copy
  1. <span style="font-size:16px;"><strong>•</strong>back()   
  2. •push_back()   
  3. •pop_back()</span>   

 

因此,标准的容器类模板vectordeque 和list可以使用,默认情况下,如果没有容器类被指定成为一个提别的stack 类,标准的容器类模板就是deque 队列。

//常用模型
stackr<int,vector<int>>;
stack<int,deque<int>>;
stack<int,list<int>>;
//默认
stack<int,deque<int>>;





实现C++  STL,栈有两个参数。

template < class T, class Container = deque<T> > class stack;

参数示意:

  • T: 元素类型
  • Container: 被用于存储和访问元素的的类型

成员函数

stack::stack

explicit stack ( const Container& ctnr = Container() );

用于构造一个栈适配器对象。

ctnr
Container object
Container is the second class template parameter (the type of the underlying container for the stack; by default:  deque<T>, see  class description).
[cpp]  view plain   copy
  1. // test_stack.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include <stack>  
  6. #include <vector>  
  7. #include <deque>  
  8. #include <iostream>  
  9.   
  10. using namespace std;  
  11.   
  12. int _tmain(int argc, _TCHAR* argv[])  
  13. {  
  14.     deque<int> mydeque(2,100);  
  15.     vector<int> myvector(2,200);  
  16.   
  17.     stack<int> first;  
  18.     stack<int> second(mydeque);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值