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;
}
运行截图: