C++ 栈stack

该博客展示了如何使用C++实现一个基于vector的模板类MyStack,并进行了基本操作如push、pop、top、size及empty的测试。同时,测试了自定义数据类型MM在自定义栈中的存储和操作,包括输出友元函数的应用。

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

 MyStack.hpp

#pragma once
//����ͨ��vectorʵ��stack
#include <vector>
#include <iostream>
using namespace std;
template <class _Ty>
class MyStack
{
public:
	MyStack() {}
	void push(_Ty data) { mem.push_back(data); }
	_Ty top() { return mem[mem.size() - 1];}
	void pop() { mem.pop_back(); }
	int size() { return mem.size(); }
	int empty() { return mem.empty();}
protected:
	vector<_Ty> mem;
};

#include <stack>
#include <iostream>
#include "MyStack.hpp"
using namespace std;
/*
	1.基本操作
	push();
	pop();
	top();
	size();
	empty();
*/
void testStack() 
{
	stack<int> intStack;
	for (int i = 0; i < 3; i++) 
	{
		intStack.push(i);
	}
	cout << "size:" << intStack.size() << endl;
	while (!intStack.empty()) 
	{
		cout << intStack.top() << "\t";
		intStack.pop();
	}
	cout << endl;
}

class MM 
{
public:
	MM(string name,int age):name(name),age(age){}
	friend ostream& operator<<(ostream& out, const MM& object);
protected:
	string name;
	int age;
};
ostream& operator<<(ostream& out, const MM& object) 
{
	out << object.name << "\t" << object.age << endl;
	return out;
}
void testUserData() 
{
	stack<MM>  mmStack;
	MM mm[3] = { {"string1",15},
		{"string2",17},
		{"string0",29} };
	for (int i = 0; i < 3; i++) 
	{
		mmStack.push(mm[i]);
	}
	while (!mmStack.empty()) 
	{
		cout << mmStack.top();
		mmStack.pop();
	}
}

void testMyStack() 
{
	MyStack<MM>  mmStack;
	MM mm[3] = { {"string1",15},
		{"string2",17},
		{"string0",29} };
	for (int i = 0; i < 3; i++)
	{
		mmStack.push(mm[i]);
	}
	while (!mmStack.empty())
	{
		cout << mmStack.top();
		mmStack.pop();
	}
}


int main() 
{
	testStack();
	testUserData();
	cout << "------------------" << endl;
	testMyStack();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值