STL编程 —— stack

stacks函数列表

empty()  堆栈为空则返回真

pop() 移除栈顶元素

push() 在栈顶增加元素

size() 返回栈中元素数目

top() 返回栈顶元素


代码1:


#include "iostream"
#include "stack"
using namespace std;

void main()
{
	//定义了容器类  具体类型 int
	stack<int> s;
	for (int i = 0; i < 5; i++)
	{
		s.push(i + 1);
	}

	//需要遍历栈元素,需要一个一个的弹出元素才能遍历
	while (!s.empty())
	{
		//获取栈顶元素
		int tmp = s.top();
		cout << tmp <<"  ";
		//弹出栈顶元素
		s.pop();
	}
	cout << endl;

	system("pause");
}


代码2:



#include "iostream"
#include "stack"
using namespace std;

void printStack(stack<int> &s)
{
	while (!s.empty())
	{
		//获取栈顶元素
		int tmp = s.top();
		cout << tmp << "  ";
		//弹出栈顶元素
		s.pop();
	}
	cout << endl;
}

void main()
{
	//定义了容器类  具体类型 int
	stack<int> s;

	for (int i = 0; i < 5; i++)
	{
		s.push(i + 1);
	}

	//需要遍历栈元素,需要一个一个的弹出元素才能遍历
	
	printStack(s);

	system("pause");
}




原文链接: STL编程 —— stack 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-9.html )

发表评论

0则评论给“STL编程 —— stack”