Stack

来源:互联网 发布:手机怎么进电脑版淘宝 编辑:程序博客网 时间:2024/04/28 19:51

Desription of Stack

 Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out)。

The underlying container may be any of the standard container class templates or some other specifically designed container class. The only requirement is that it supports the following operations:

  • back()
  • push_back()
  • pop_back()
Therefore, the standard container class templates vectordeque and list can be used. By default, STL uses deque.

 

 

Operation of Stack

 

push

pop

 

 

 

 

 

The function of Stack:

FILO

 

 

C++中的实现

 

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

  • T: Type of the elements.
  • Container: Type of the underlying container object used to store and access the elements.

Member functions



Application example:

 

1) 左右括号匹配问题(见我的数据结构算法库例子大全)

 

// stack::push/pop#include <iostream>#include <stack>using namespace std;int main (){
  cout<<"Please input the expressions"<<endl;
  cin<<;
  String str;
  
  stack<String> mystack;  for (int i=0; i<str.length; ++i) {
if (str[i] =="(")
mystack.push(i); 
else if (str[i] ==")")
  {
if ( stack.empty() ) {
cout<<"Illegal expression";
return -1;
} else {
   cout<<"pop "<<mystack.top();
mystack.pop( );
  
}
 }
  return 0;}


 

Reference:


http://www.cplusplus.com/reference/stack/stack/

原创粉丝点击