每日一题18:栈

用C++写了1个栈模板,其间用了1些《Effective C++》的准则,记录在这里喽。这个类还没有做到异常安全,以后改进!
Stack.h文件。

#ifndef _STACK_H_
#define _STACK_H_

namespace MyDataStructure
{
template <typename T>
class Stack
{
private:
int Capacity;
int Top;
T* Vals;

bool null()
{
return Capacity == 0;
}
void init(int capacity)
{
Capacity = capacity;
Top = 0;
Vals = new T[capacity];
}
void copy(const Stack& s)
{
Capacity = s.Capacity;
Top = s.Top;
Vals = NULL;
if(s.Capacity != 0)
{
Vals = new T[Capacity];
memcpy(Vals,s.Vals,Capacity*sizeof(T));
}
}

void destroy()
{
if(Vals != NULL) delete []Vals;
Top = 0;
Capacity = 0;
}
public:
Stack() : Capacity(0),Top(0),Vals(NULL){};
Stack(int capacity)
:Capacity(capacity),Top(0)
{
Vals = new T[capacity];
}
Stack(const Stack& s)
{
copy(s);
}
Stack& operator = (const Stack& s)
{
if(this == &s) return *this;
destroy();
copy(s);
return *this;
}
~Stack()
{
destroy();
}
bool resize(int capacity)
{
if(capacity <= 0) return false;
if(capacity == Capacity) return true;
if(!null())
{

T* vals = new T[capacity];
if(capacity >= Top)
{
memcpy(vals,Vals,Top*sizeof(T));
}
else
{
memcpy(vals,Vals,capacity*sizeof(T));
Top = capacity;
}
Capacity = capacity;
delete []Vals;
Vals = vals;
}
else
init(capacity);
return true;
}
bool push(T val)
{
if(!full() && !null())
{
Vals[Top++] = val;
return true;
}
return false;
}
bool pop(T& val)
{
if(!null() && !empty())
{
val = Vals[--Top];
return true;
}
return false;
}
bool top(T &val)
{
if(!null() && !empty())
{
val = Vals[Top - 1];
return true;
}
return false;
}
void clear()
{
Top = 0;
}
void size()
{
return Top;
}
bool empty()
{
return Top == 0;
}
bool full()
{
return Top == Capacity;
}

};

}
#endif

下面是测试函数:
StackTest.cpp

// StackTest.cpp : 定义控制台利用程序的入口点。
//

#include "stdafx.h"
#include "Stack.h"
#include <iostream>

using namespace MyDataStructure;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
Stack<int> s1(10);
for (int i = 1; i < 11; ++i)
{
s1.push(i);
}

Stack<int> s2(s1);
s1.resize(20);
for (int i = 1; i < 11; ++i)
{
int val;
if(s1.pop(val))
{
cout<<val<<' ';
}
}
cout<<endl;

for (int i = 1; i < 11; ++i)
{
int val;
if(s2.pop(val))
{
cout<<val<<' ';
}
}
cout<<endl;
return 0;
}

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » 每日一题18:栈

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡