1. 程式人生 > >C++ 棧

C++ 棧

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<br></code></div>