当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ stack push()、pop()用法及代码示例


堆栈是一种具有LIFO(后进先出)类型的容器适配器,其中在一端添加了一个新元素,而(顶部)仅从该端删除了一个元素。

stack::push()

push()函数用于在堆栈顶部插入元素。元素被添加到堆栈容器中,并且堆栈的大小增加了1。

用法:


stackname.push(value)
参数:
The value of the element to be inserted is passed as the parameter.
Result:
Adds an element of value same as that of 
the parameter passed at the top of the stack.

例子:

Input:  mystack
          mystack.push(6);
Output: 6
 
Input:  mystack
          mystack.push(0);
          mystack.push(1);
Output: 0, 1

错误和异常

1.如果传递的值与堆栈类型不匹配,则显示错误。
2.如果参数没有引发任何异常,则不显示任何引发异常的保证。

// CPP program to illustrate 
// Implementation of push() function 
#include <iostream> 
#include <stack> 
using namespace std; 
  
int main() 
{ 
    // Empty stack 
    stack<int> mystack; 
    mystack.push(0); 
    mystack.push(1); 
    mystack.push(2); 
  
    // Printing content of stack 
    while (!mystack.empty()) { 
        cout << ' ' << mystack.top(); 
        mystack.pop(); 
    } 
}

输出:

2 1 0
Note that output is printed on the basis of LIFO property
stack::pop()

pop()函数用于从堆栈顶部删除元素(堆栈中的最新元素)。元素被移到堆栈容器,堆栈的大小减小1。

用法:

stackname.pop()
参数:
No parameters are passed.
Result:
Removes the newest element in the stack
or basically the top element.

例子:

Input:  mystack = 0, 1, 2
          mystack.pop();
Output: 0, 1
 
Input:  mystack = 0, 1, 2, 3, 4, 5
          mystack.pop();
Output: 0, 1, 2, 3, 4

错误和异常

1.如果传递参数,则显示错误。
2.不显示异常抛出保证。

// CPP program to illustrate 
// Implementation of pop() function 
#include <iostream> 
#include <stack> 
using namespace std; 
  
int main() 
{ 
    stack<int> mystack; 
    mystack.push(1); 
    mystack.push(2); 
    mystack.push(3); 
    mystack.push(4); 
    // Stack becomes 1, 2, 3, 4 
  
    mystack.pop(); 
    mystack.pop(); 
    // Stack becomes 1, 2 
  
    while (!mystack.empty()) { 
        cout << ' ' << mystack.top(); 
        mystack.pop(); 
    } 
}

输出:

2 1
Note that output is printed on the basis of LIFO property

应用:
给定多个整数,将它们添加到堆栈中,然后在不使用size函数的情况下找到堆栈的大小。

Input:5, 13, 0, 9, 4
Output:5

算法
1.将给定的元素一张一张地推入堆栈容器。
2.继续弹出堆栈中的元素直到其变空,然后递增计数器变量。
3.打印计数器变量。

// CPP program to illustrate 
// Application of push() and pop() function 
#include <iostream> 
#include <stack> 
using namespace std; 
  
int main() 
{ 
    int c = 0; 
    // Empty stack 
    stack<int> mystack; 
    mystack.push(5); 
    mystack.push(13); 
    mystack.push(0); 
    mystack.push(9); 
    mystack.push(4); 
    // stack becomes 5, 13, 0, 9, 4 
  
    // Counting number of elements in queue 
    while (!mystack.empty()) { 
        mystack.pop(); 
        c++; 
    } 
    cout << c; 
}

输出:

5


相关用法


注:本文由纯净天空筛选整理自AyushSaxena大神的英文原创作品 stack push() and pop() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。