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


C++ Stack push()用法及代码示例

C++ Stack push()函数用于在栈顶添加新元素。如果我们有一个堆栈类型的数组并且通过使用 push() 函数,我们可以在堆栈中插入新元素。元素被插入到栈顶。最开始插入的元素在最后被删除,反之亦然,因为堆栈遵循 LIFO 原则。

用法

void push (const value_type& value);

参数

value: 参数表示元素被初始化的值。该参数指定新插入元素的值。元素 'val' 在函数执行后成为新的栈顶元素。

返回值

该函数只插入元素,不返回任何值。函数的返回类型可以认为是void。

例子1

//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。

#include <iostream>
#include <stack>
int main()
{
         std::stack<int> newstack;
         for(int j= 0; j<5; j++)
         newstack.push(j);
         std::cout << "Poping the elements out of the stack??.";
         while (!newstack.empty () )
         {
       std::cout<<" " << newstack.top ();
        newstack.pop();
    }
    

std::cout<<"\n";
return 0;
}

输出:

Poping the elements out of the stack..... 4 3 2 1 0

例子2

#include <iostream>
#include <stack>
int main()
{
    
        std::stack<int> newstack;
        newstack.push(69);
        newstack.push(79);
        newstack.push(80);
        while (!newstack.empty())
        {
            std::cout<<" " << newstack.top ();
            newstack.pop();
        }
        return 0;
}

输出:

90 85 80 79 69

例子3

//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。

#include <iostream>
#include <stack>
int main()
{
    std::stack<int> newstack; 
    newstack.push(11);
    newstack.push(22);
    newstack.push(33);
    newstack.push(44);
    std::cout << "Popping out elements?";
    newstack.pop();
    newstack.pop();
    while (!newstack.empty () )
    {
        std::cout << " " << newstack.top();
        newstack.pop();
    }
    std::cout<<'\n';
    return 0;
}

输出:

Popping out elements... 22 11  

示例 4

//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。

#include <iostream>
#include <stack>
int main()
{
    std::stack<int> a,b;
    a.push(5); a.push(8); a.push(50);
    b.push(132); b.push(45);
    std::cout<<"Size of a:"<<a.size();
    std::cout<<"\n Size of b:" <<b.size();
    return 0;
}

输出:

Size of a:3
Size of b:2 

复杂度

对底层容器的推回进行一次调用,这是完成元素上的插入操作所必需的。

数据竞争

对容器和包含的元素进行了修改。添加新元素会修改所有底层堆栈元素。

异常安全

提供等同于对底层容器对象执行的操作的保证。





相关用法


注:本文由纯净天空筛选整理自 C++ Stack push() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。