【c++】模拟实现栈 类模板(Stack的基本操作)

本文档介绍了如何在C++环境下,使用类模板来模拟实现栈的数据结构,包括栈的基本操作,如压栈、弹栈等。适用于Windows 7 x64系统,基于Visual Studio 2012编译环境。
摘要由CSDN通过智能技术生成

// 坏境 win7  x64 vs2012

#include <iostream>
#include <cassert>
using namespace std;

template <typename T>
class Stack
{
public:
	// 构造函数
	explicit Stack(const size_t capacity = 10)
		:_size(0)
		,_capacity(10)
	{
		// 最小分配10个 大于10 则分配用户指定的大小
		_capacity = (_capacity > capacity)? _capacity : capacity;
		_array = new T[_capacity];
	}

	// 拷贝构造函数
	explicit Stack(const Stack<T>&  s)
	{
		_array = new T[s._capacity];
		_capacity = s._capacity;
		_size = s._size;
		for (size_t idx = 0; idx < _size; ++idx)
		{
			_array[idx] = s._array[idx];
		}
	}

	// 赋值重载 简洁版本
	Stack& operator=(const	Stack<T>& s)
	{
		if (this != &s)
		{
			Stack temp(s);
			std::swap(_array, temp._array);
			_size = s._size;
			_capacity = s._capacity;
		}
		return *this;
	}

	// 获取当前栈顶
	T& Top()const
	{
		assert(!Empty());  // 断言
		return _array[_size -1];
	}

	/
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值