[C++] How to use stack

How to use stack in C++

The stack template class (declared in the header file stack) is an adapter class that provides a typical stack interface to the underlying class (vector by default).
The stack template has more restrictions than the vector. Not only does it not allow random access to stack elements , it does not even allow traversal of the stack . It restricts its use to the basic operations of defining the stack, that is, it can push to the top of the stack, pop elements from the top of the stack, view the value of the top of the stack, check the number of elements, and test whether the stack is empty.

1. The header file contains

#include <stack>

2. Constructor

1. //默认构造函数
   stack<int> first;//创建一个空的stack

2. //复制构造函数,使用已有的stack创建新的stack
   stack<int, list<int> >   s1;
   stack<int, list<int> >   s2(s1);//利用 s1 ,创建一个以双向链表为底层容器的空堆栈对象 s2 

   //使用已创建的deque创建stack
   deque<int> mydeque (3,100);          // 包含3个元素deque
   stack<int> second (mydeque);         // 使用deque初始化stack

   //创建vector为底层的stack,和使用已有stack初始化新的stacck
   std::stack<int,std::vector<int> > third;  // 使用vector创建的空stack
   std::stack<int,std::vector<int> > fourth (myvector);

3. Operation

grammar:

  ==
  <=
  >=
  <
  >
  !=

All of these operations can be used on the stack. Equality means that the stack has the same elements in the same order.

4. Overview of method functions

1. empty()	堆栈为空则返回真

2. pop()	移除栈顶元素

3. push()	在栈顶增加元素

4. size()	返回栈中元素数目

5. top()	返回栈顶元素

5. Method function prototype and simple explanation

empty
Syntax:
bool empty();
as the current stack is empty, empty () function returns true otherwise false.

pop
syntax: The
void pop();
pop() function removes the top element in the stack.

Push
syntax: The
void push( const TYPE &val );
push() function pushes the val value onto the stack, making it the first element on the top of the stack. Such as:

    stack<int> s;
    for( int i=0; i < 10; i++ )
      s.push(i);

Size
syntax: The
size_type size();
size() function returns the number of elements in the current stack. Such as:

    stack<int> s;
    for( int i=0; i < 10; i++ )
      s.push(i);
    cout << "This stack has a size of " << s.size() << endl;

top
syntax: The
TYPE &top();
top() function returns a reference to the top element of the stack. For example, the following code displays and clears a stack.

    while( !s.empty() ) {
    
    
      cout << s.top() << " ";
      s.pop();
    }

Guess you like

Origin blog.csdn.net/phdongou/article/details/114248412