流沙团
STL编程 —— stack
2016-5-10 流沙团


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");
}












发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容