c++ 用类模版实现数组类

最近c++学到数组类,写了代码将他实现,基本具有vector类的功能


#include<iostream>
#include<string>
#include<cassert>
using namespace std;
template<class T>
class Array
{
public:
//构造函数
Array(int sz = 50){
assert(sz >= 0);
size = sz;
list = new T[size];
}
//复制构造函数
Array(const Array<T>&a){
size = a.size;
list = new T[size];
for (int i = 0; i < size; i++){
list[i] = a.list[i];
}
}
~Array(){
delete[] list;
}
//=等号运算符重载
Array<T>& operator=(const Array<T> &rhs){
if (&rhs != this){
if (size != rhs.size){
delete [] list;
size = rhs.size;
list = new T[size];
}
for (int i = 0; i < size; i++){
list[i] = rhs.list[i];
}
}
return *this;
}
//[]下标运算符重载
T & operator [] (int i){
assert(i >= 0 && i < size);
return list[i];
}
const T & operator[](int i)const{
assert(i >= 0 && i < size);
return list[i];
}
//重载指针转换运算符,将Array类的对象名转换为T类型的指针
//指向当前对象中的私有数组,
//因而可以像使用普通数组首地址一样使用Array类的对象名
operator T * (){
return list;
}
operator const T *()const{
return list;
}
//获得当前数组大小
int getSize()const{
return size;
}
//重设当前数组大小
void resize(int sz){
assert(sz >= 0);
if (sz == size)
return;
T * newList = new T[sz];
int n = (sz < size) ? sz : size;
for (int i = 0; i < n; i++){
newList[i] = list[i];
}
delete[] list;
list = newList;
size = sz;
}
//添加数据
void add(const T x){
assert(size >= 0);
size++;
T * newList = new T[size];
for (int i = 0; i < size-1; i++){
newList[i] = list[i];
}
newList[size-1] = x;
delete[] list;
list = newList;

}
//移除数据
void remove(const int n){
assert(size >= 0 && n < size);
T * newlist = new T[--size];
for (int i = 0; i < n; i++){
newlist[i] = list[i];
}
for (int i = n+1; i < size+1; i++){
newlist[i-1] = list[i];
}
delete[] list;
list = newlist;
}
//插入数据
void insert(const int n,const int x){
assert(size >= 0 && n < size);
T * newlist = new T[++size];
for (int i = 0; i < n; i++){
newlist[i] = list[i];
}
newlist[n] = x;
for (int i = n + 1; i < size ; i++){
newlist[i] = list[i-1];
}
delete[] list;
list = newlist;
}
private:

T* list;
int size;
};
int main(){
Array<int> a(4);
cout << "size=" << a.getSize() << endl;
for (int i = 0; i < a.getSize(); i++){
a[i] = i;
}
for (int i = 0; i < a.getSize(); i++){
cout << a[i] << endl;
}
cout << "***********test***************" << endl;
cout << "add " << endl;
a.add(53);
for (int i = 0; i < a.getSize(); i++){
cout << a[i] << endl;
}
cout << "size=" << a.getSize()<<endl;
cout << "***********test***************" << endl;
cout << "remove" << endl;
a.remove(2);
for (int i = 0; i < a.getSize(); i++){
cout << a[i] << endl;
}
cout << "size=" << a.getSize() << endl;
cout << "***********test***************" << endl;
cout << "insert" << endl;
a.insert(2, 100);
for (int i = 0; i < a.getSize(); i++){
cout << a[i] << endl;
}
cout << "size=" << a.getSize() << endl;
cout << "***********test***************" << endl;
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值