C++ 学习练手 - 数组型栈的模板实现
2007-11-01 17:07
761 查看
#ifndef __STACKPRACTICE_H__
#define __STACKPRACTICE_H__ 1
namespace FengChen
...{
template <class Type> class Stack;
template <class T>
std::ostream& operator<<(std::ostream& os, const Stack<T>& S)
...{
os<<"Stack:< ";
for(int i = 0; i < S.m_Length; i++) os<<S.m_Array[i]<<" ";
os<<" --Top>";
return os;
}
template <class Type> class Stack
...{
friend std::ostream& operator<< <Type> (std::ostream&, const Stack<Type>&);
public:
Stack():m_Capicity(64 * 1024 / sizeof(Type)),m_Length(0),m_Array(0)
...{
if( (m_Array = new Type[m_Capicity]) == 0)
throw std::runtime_error("Initialize failed, not enough memory!");
}
Stack(int Size):m_Length(0),m_Array(0)
...{
assert(Size > 1);
m_Capicity = Size;
if( (m_Array = new Type[m_Capicity]) == 0)
throw std::runtime_error("Initialize failed, not enough memory!");
}
~Stack()
...{
delete[] m_Array;
m_Array = 0;
}
inline int Length() const...{return m_Length;}
inline int Capacity() const...{return m_Capicity;}
const Type& Top() const ...{ return m_Array[m_Length - 1]; }
void Push(const Type& value)
...{
if(m_Length + 1 > m_Capicity) this->Resize();
m_Array[m_Length++] = value;
}
const Type& Pop()
...{
if(m_Length < 1) throw std::runtime_error("Stack is null!");
return m_Array[m_Length--];
}
private:
int m_Capicity;
int m_Length;
Type* m_Array;
void Resize()
...{
int newSize = 2*m_Capicity;
int* newArray = 0;
if((newArray = new Type[newSize] ) == 0)
throw std::runtime_error("Resize failed, not enough memory!");
memmove_s(newArray, m_Capicity*sizeof(Type), m_Array, m_Capicity*sizeof(Type));
delete [] m_Array;
m_Capicity = newSize;
m_Array = newArray;
}
};
}
#endif
相关文章推荐
- C++ 学习练手 - 数组型队列的模板实现
- C++ 学习练手 - 双向链表的模板实现
- C++入门学习:类模板的使用(函数在类的内外实现的不同)
- C++模板学习之栈的实现
- C++类模板定义与实现的分离—学习C++数据抽象和问题求解
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- C++学习 【4.4】 利用函数实现指定的功能---函数的重载、函数模板、有默认参数的函数
- First head 设计模式学习c++实现------模板方法模式(Template method pattern)
- C++模板学习之单链表的实现
- c++ 模板学习笔记:函数模板实现数组通用排序和遍历打印(权哥)
- c++学习--模板--实现my_vector
- 数据结构学习第一篇--C++实现单链表模板
- 学习笔记-简单模板链表类的C++实现 15/10/25
- c++ 模板学习笔记:类模板和函数模板实现pair(权哥)
- C++利用链表与模板实现栈
- 吴恩达老师深度学习视频课笔记:逻辑回归公式推导及C++实现
- 数据结构图文解析之:数组、单链表、双链表介绍及C++模板实现
- GirdView学习之六 使用模板列实现多行删除
- 【data structure】线性表简单模板c++实现
- c++ 实现模板方法模式