#if 1
#include<iostream>
#include<stack>
using namespace std;
void test01() {
//初始化
stack<int> s1;
stack<int> s2(s1);
//stack操作
s1.push(10);
s1.push(20);
s1.push(30);
s1.push(40);
cout << "栈顶元素:" << endl;
cout<<s1.top()<<endl;
//打印栈容器数据
cout << "栈容器内容为:" << endl;
while (!s1.empty())
{
cout << s1.top() << endl;
s1.pop();
}
cout << "size:";
cout << s1.size() << endl;
}
//作业1:栈容器存放对象指针
//作业2:栈容器存放对象
int main() {
test01();
return 0;
}
#endif
运行结果:
作业:
#if 1
#include<iostream>
#include<stack>
using namespace std;
class Person {
public:
Person(int Age,int Id):age(Age),id(Id){}
public:
int age;
int id;
};
void test01()
{
stack<Person> sp;
Person p1 = { 23,1 };
Person p2 = { 24,2 };
Person p3 = { 25,3 };
sp.push(p1);
sp.push(p2);
sp.push(p3);
while (!sp.empty()) {
Person p = sp.top();
cout << p.age << " " << p.id << endl;
sp.pop();
}
}
void test02()
{
stack<Person*> sp;
Person p1 = { 23,1 };
Person p2 = { 24,2 };
Person p3 = { 25,3 };
sp.push(&p1);
sp.push(&p2);
sp.push(&p3);
while (!sp.empty()) {
Person *p = sp.top();
cout << (*p).age << " " << (*p).id << endl;
sp.pop();
}
}
int main() {
cout << "打印存放对象的结果:" << endl;
test01();
cout << "打印存放对象指针的结果:" << endl;
test02();
return 0;
}
#endif