STL11-stack容器

本文介绍了使用C++标准模板库(STL)中的栈容器进行数据操作的方法,包括栈的基本操作及如何存放对象和对象指针,并通过示例展示了具体的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值