本文介绍堆栈stack的用法示例。stack是一种先进后出,后进先出的容器。下面是示例代码。
#include "iostream"
using namespace std;
#include "stack"
void main41()
{
stack<int> s;
for (int i=0;i<10;i++)
{
s.push(i+1);
}
cout << "栈的大小:" << s.size() << endl;
while (!s.empty())
{
int tmp = s.top();// 获取栈顶元素
cout << tmp << " ";
s.pop();// 弹出栈顶元素
}
cout << endl;
}
//teacher 结点
class Teacher
{
public:
int age;
char name[32];
public:
void printT()
{
cout << "age:" << age << endl;
}
protected:
private:
};
void main42()
{
Teacher t1,t2,t3;
t1.age = 31;
t2.age = 32;
t3.age = 33;
stack<Teacher> s;
s.push(t1);
s.push(t2);
s.push(t3);
while (!s.empty())
{
Teacher tmp = s.top();
tmp.printT();
s.pop();
}
}
void main43()
{
Teacher t1,t2,t3;
t1.age = 31;
t2.age = 32;
t3.age = 33;
stack<Teacher *> s;
s.push(&t1);
s.push(&t2);
s.push(&t3);
while(!s.empty())
{
Teacher *p = s.top();
p->printT();
s.pop();
}
}
void main()
{
//main41();
//main42();
main43();
cout << "hello..."<< endl;
system("pause");
}