《CPlusPlusPrimer》第四章编程源码——iStack类的简单实现

iStack.h

#ifndef _CPlusPlusPrimer_chapter4_istack
#define _CPlusPlusPrimer_chapter4_istack

#include <vector>

namespace Icanth_CPlusPlusPrimer
{
	template<class elemType>
	class iStack
	{
	public:
		iStack(int capacity)
			: _stack( capacity ), _top( 0 ) {} // 创建栈元素

		bool pop(elemType &value);
		bool push(elemType value);
		
		bool full();
		bool empty();
		void display();

		int size();

	private:
		int _top;
		std::vector<elemType> _stack;
	};
}

#endif


iStack.cpp

#include "iStack.h"

namespace ICP = Icanth_CPlusPlusPrimer;

template<class elemType>
bool ICP::iStack<elemType>::pop(elemType &top_value)
{
	if( empty() )
	{
		return false;
	}

	top_value = _stack[--_top];

#ifdef _DEBUG_
	cout << "iStack<elemType>::pop():" << top_value << endl;
#endif

	return true;
}

template<class elemType>
inline bool ICP::iStack<elemType>::empty()
{
	return _top ? false : true;
}

template<class elemType>
inline bool ICP::iStack<elemType>::full()
{
	return _top < _stack.size() ? false : true;
}

template<class elemType>
bool ICP::iStack<elemType>::push(elemType value)
{
	if(full())
		return false;

	_stack[_top++] = value;
#ifdef _DEBUG_
	cout << "IStack<elemType>::push(" << value << ")\n";
#endif
	return true;
}

template<class elemType>
inline int ICP::iStack<elemType>::size()
{
	return _top;
}

template<class elemType>
void ICP::iStack<elemType>::display()
{
	if(!size())
	{
		cout << "( 0 )\n";
		return;
	}

	cout << "(" << size() << ")(bot: ";
	for(int ix = 0; ix < _top; ++ix)
		cout << _stack[ix] << " ";
	cout << " :top )\n";
}


test.cpp

#include "iStack.cpp"

#include <iostream>

namespace  ICP = Icanth_CPlusPlusPrimer;
using namespace std;

int main()
{
	using ICP::iStack;

	iStack<int> stack(10);
	int x = 0;

	stack.push(1);
	stack.push(2);
	stack.push(3);
	stack.pop(x);

	stack.display();	
	
	return 0;
}


运行截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值