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

来源:互联网 发布:巫师3狼派装备数据 编辑:程序博客网 时间:2024/06/05 14:40

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

 
分享到:
    发布时间:2014-10-8  


    本文导语: c++ stl栈stack介绍C++ Stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构。c++ stl栈stack的头文件为:#include <stack>c++ stl栈stack的成员函数介绍操作 ...
(为尊重原作者,特说明以下此文转自http://www.169it.com/article/2839007600903800247.html)

c++ stl栈stack介绍

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

c++ stl栈stack的头文件为

#include <stack> 

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

操作比较和分配堆栈

empty()堆栈为空则返回真

pop()移除栈顶元素

push()在栈顶增加元素

size()返回栈中元素数目

top()返回栈顶元素

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;  
}

以下部分复制自百度知道:

stack() 声明一个空栈;

stack(mycont) 声明一个初始内容复制自mycont的栈;

函数:

push 将一个新元素压倒栈中;

pop 弹出栈中的元素,如果栈为空,结果未定义,函数返回void;

top 存取栈的顶端元素,如果栈为空,结果未定义,返回的是一个引用;

empty 测试栈是否为空;

size 获得栈中元素的个数;



原创粉丝点击