C++ Stack 中的 push函数

首页 / C++入门教程 / C++ Stack 中的 push函数

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

push - 语法

void push (const value_type& value);

push - 参数

value   -  该参数表示元素要初始化为的值。该参数指定新插入的元素的值。函数执行后,元素" val"成为堆栈中新的顶层元素。

push - 返回值

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

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-stack-push-function.html

来源:LearnFk无涯教程网

push - 例子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

push - 例子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

push - 例子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  

push - 例子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 

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Linux性能优化实战 -〔倪朋飞〕

Vue开发实战 -〔唐金州〕

Kafka核心技术与实战 -〔胡夕〕

互联网人的英语私教课 -〔陈亦峰〕

正则表达式入门课 -〔涂伟忠〕

容器实战高手课 -〔李程远〕

超级访谈:对话张雪峰 -〔张雪峰〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

零基础GPT应用入门课 -〔林健(键盘)〕

好记忆不如烂笔头。留下您的足迹吧 :)