C ++ Stack push()函数用于在堆栈顶部添加新元素。如果我们有一个类型为stack的数组,并且通过使用push()函数,我们可以在堆栈中插入新元素。元素将插入到堆栈的顶部。随着堆栈遵循LIFO原理,最开始插入的元素将在末尾删除,反之亦然,因为堆栈遵循后进先出原则。
void push (const value_type& value);
value:该参数表示元素被初始化为的值。该参数指定新插入的元素的值。函数执行后,元素“ val”成为堆栈中新的顶层元素。
该函数仅插入元素,不返回任何值。该函数的返回类型可以认为是无效的。
//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> newstack;
for(int j= 0; j<5; j++)
newstack.push(j);
cout << "从堆栈中弹出元素......";
while (!newstack.empty () )
{
cout<<" " << newstack.top ();
newstack.pop();
}
cout<<"\n";
return 0;
}输出:
从堆栈中弹出元素..... 4 3 2 1 0
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> newstack;
newstack.push(69);
newstack.push(79);
newstack.push(80);
while (!newstack.empty())
{
cout<<" " << newstack.top ();
newstack.pop();
}
return 0;
}输出:
90 85 80 79 69
//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> newstack;
newstack.push(11);
newstack.push(22);
newstack.push(33);
newstack.push(44);
cout << "弹出元素...";
newstack.pop();
newstack.pop();
while (!newstack.empty () )
{
cout << " " << newstack.top();
newstack.pop();
}
cout<<'\n';
return 0;
}输出:
弹出元素... 22 11
//该程序用于通过插入简单的整数值来演示堆栈的push()函数的使用。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> a,b;
a.push(5); a.push(8); a.push(50);
b.push(132); b.push(45);
cout<<"a的大小: "<<a.size();
cout<<"\n b的大小:" <<b.size();
return 0;
}输出:
a的大小: 3 b的大小:2
一个调用对底层容器进行回推,这对于完成元素上的插入操作是必要的。
对容器和包含的元素进行修改。添加一个新元素将修改所有底层堆栈元素。
提供与在底层容器对象上执行的操作等效的保证。