C++ Stack push()函数用于在堆栈顶部添加新元素。如果我们有一个类型为stack的数组,并且通过使用push()函数,我们可以在堆栈中插入新元素。元素将插入到堆栈的顶部。随着堆栈遵循LIFO原则,最开始插入的元素将在末尾删除,反之亦然。
void push (const value_type& value);
value - 该参数表示元素要初始化为的值。该参数指定新插入的元素的值。函数执行后,元素" val"成为堆栈中新的顶层元素。
该函数仅插入元素,不返回任何值。该函数的返回类型可以认为是无效的。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-stack-push-function.html
来源:LearnFk无涯教程网
//该程序用于通过插入简单的整数值来演示堆栈的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
#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
//该程序用于通过插入简单的整数值来演示堆栈的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
//该程序用于通过插入简单的整数值来演示堆栈的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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)