先进后出
#include<iostream>
#include<stack>
using namespace std;
//基本数据类型
void test()
{
stack<int> s;
//入栈
for(int i = 0; i < 10; i++)
{
s.push(i+1);
}
cout<<"栈的大小:"<<s.size()<<endl;
//出栈
while (!s.empty())
{
int temp = s.top(); //获取栈顶元素
cout<<temp<<" ";
s.pop(); //弹出栈顶元素
}
}
//teacher
class teacher
{
public:
int age;
char name[20];
public:
void printT()
{
cout<<"age: "<<age<<endl;
}
};
//自定义数据类型
void test1()
{
teacher t1,t2,t3;
t1.age = 10;
t2.age = 20;
t3.age = 30;
stack<teacher> s1;
s1.push(t1);
s1.push(t2);
s1.push(t3);
while (!s1.empty())
{
teacher temp = s1.top(); //获取栈顶元素
temp.printT();
s1.pop();
}
}
//自定义数据类型指针
void test2()
{
teacher t1,t2,t3;
t1.age = 10;
t2.age = 20;
t3.age = 30;
stack<teacher*> s2;
s2.push(&t1);
s2.push(&t2);
s2.push(&t3);
while (!s2.empty())
{
teacher* temp = s2.top(); //获取栈顶元素
temp->printT(); //等价 (*temp).printT();
s2.pop();
}
}
int main()
{
test();
test1();
test2();
return 0;
}