c++ stl栈容器stack的pop(),push()等用法介绍及头文件

来源:互联网 发布:linux下xampp mysql 编辑:程序博客网 时间:2024/06/05 18:21

c++ stl栈stack介绍

C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构。

c++ stl栈stack的头文件为

#include <stack> 

c++ stl栈stack的成员函数介绍

操作 比较和分配堆栈

empty() 堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素

c++ stl栈stack用法代码举例1

#include "stdafx.h"  
#include <stack>  
#include <vector>  
#include <deque>  
#include <iostream>  
   
using namespace std;  
   
int _tmain(int argc, _TCHAR* argv[])  
{  
    deque<int> mydeque(2,100);  
    vector<int> myvector(2,200);  
   
    stack<int> first;  
    stack<int> second(mydeque);  
   
    stack<int,vector<int> > third;  
    stack<int,vector<int> > fourth(myvector);  
   
    cout << "size of first: " << (int) first.size() << endl;  
    cout << "size of second: " << (int) second.size() << endl;  
    cout << "size of third: " << (int) third.size() << endl;  
    cout << "size of fourth: " << (int) fourth.size() << endl;  
   
   
    return 0;  
}

c++ stl栈stack用法代码举例2

// stack::empty  
#include <iostream>  
#include <stack>  
using namespace std;  
   
int main ()  
{  
  stack<int> mystack;  
  int sum (0);  
   
  for (int i=1;i<=10;i++) mystack.push(i);  
   
  while (!mystack.empty())  
  {  
     sum += mystack.top();  
     mystack.pop();  
  }  
   
  cout << "total: " << sum << endl;  
     
  return 0;  
}

 c++ stl栈stack用法代码举例3

// stack::push/pop  
#include <iostream>  
#include <stack>  
using namespace std;  
   
int main ()  
{  
  stack<int> mystack;  
   
  for (int i=0; i<5; ++i) mystack.push(i);  
   
  cout << "Popping out elements...";  
  while (!mystack.empty())  
  {  
     cout << " " << mystack.top();  
     mystack.pop();  
  }  
  cout << endl;  
   
  return 0;  
}
 

 c++ stl栈stack用法代码举例4

#include <iostream>  
#include <stack>  
using namespace std;  
   
int main ()  
{  
  stack<int> mystack;  
   
  for (int i=0; i<5; ++i) mystack.push(i);  
   
  cout << "Popping out elements...";  
  while (!mystack.empty())  
  {  
     cout << " " << mystack.top();  
     mystack.pop();  
  }  
  cout << endl;  
   
  return 0;  
}

文章摘自 http://www.169it.com/article/2839007600903800247.html
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 qq没有银行卡转不出钱怎么办 qq钱包限制一万怎么办 qq余额超过20万怎么办 扣扣忘记了密码怎么办 qq钱包发不出来怎么办 qq支付密码忘了怎么办? 扣扣上转账错了怎么办 qq绑卡存在异常怎么办 微信没绑银行卡忘记支付密码怎么办 微信的自动扣费怎么办 不小心把钱充到微信财付通该怎么办 财付通用什么充值卡充值话费怎么办 苹果手机灯坏了怎么办 手机电灯不亮了怎么办? 苹果手机相机坏了怎么办 苹果5s手机背光灯不亮怎么办 苹果5s灯控坏了怎么办 微信q币冲错号码怎么办 支付宝转账到之前号码怎么办 qq红包收不了钱怎么办 qq抢红包要实名认证怎么办 支付宝被骗冲q币怎么办 qq发红包发错了怎么办 qq红包发不出来怎么办 qq红包发多了怎么办 qq发红包要短信验证怎么办 不是qq好友发了红包怎么办 苹果手机升级后支付宝打不开怎么办 qqq币充了没进帐怎么办 怎么办q币换成qq余额 支付宝qb冲多了怎么办 微信没钱怎么办怎么赚 忘记微信支付密码怎么办 手机设备注册达上限怎么办 在新手机上登微信需要验证怎么办 手机号被限制注册qq号怎么办 手机互换了微信怎么办 微信申诉只有一位好友怎么办 微信申诉没有好友怎么办 四川电信多余的话费怎么办 四川电信话费多了怎么办