C++ stack push()
C++ stack push()函数
C++堆栈push()函数用于在堆栈顶部添加新元素。如果我们有一个类型为stack的数组,并且通过使用push()函数,我们可以在堆栈中插入新元素。元素将插入到堆栈的顶部。最先插入的元素在末尾被删除,反之亦然,因为堆栈遵循LIFO原则。
语法
void push (const value_type& value);
参数
vlaue: 该参数表示元素被初始化为的值。该参数指定新插入的元素的值。元素'val'成为函数执行后堆栈中新的顶层元素。
返回值
该函数仅插入元素,不返回任何值。该函数的返回类型可以认为是无效的。
示例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;
}
输出:
示例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;
}
输出:
复杂度
将对基础容器上的推回进行一次调用,这对于完成对元素的插入操作是必需的。
数据竞争
对容器及其包含的元素进行了修改。添加新元素会修改所有基础堆栈元素。
异常安全性
保证与在基础容器对象上执行的操作等效。