您的位置:首页 > 其它

理解向量vector的一些实现细节

2017-10-26 10:15 483 查看
#include <iostream>

using namespace std;

enum ErrorType
{
invalidArraySize, memoryAllocFail, indexOutOfRange
};

const char*ErrorList[]={"invalidArraySize","memoryAllocFail","indexOutOfRange"};

template <class T>
class MyVector
{
public:
MyVector(int sz=50);
MyVector(const MyVector<T>& V);
~MyVector();
MyVector& operator=(const MyVector& V);
T& operator[](int i);
operator T*(); // 实现强制类型转换 MyVector---> T*;
int Size();
void resize(int sz);
void Error(ErrorType err);
private:
T *Array;
int size;
};

template<class T>
void MyVector<T>::Error(ErrorType err)
{
cout << ErrorList[err] << endl;
exit(1);
}

template<class T>
MyVector<T>::MyVector<T>(int sz)
{
if(sz<=0)
{
Error(invalidArraySize);
}
else
{
size = sz;
Array = new T[size];
if(Array==NULL)
Error(memoryAllocFail);

}

}

template<class T>
MyVector<T>::MyVector(const MyVector<T>& V)
{
int n = V.size;
size = n;
Array = new T
;
if(Array==NULL)
Error(memoryAllocFail);

T*org_array = Array;
T*new_array = V.Array;

while(n--)
*org_array++ = *new_array++;
}

template<class T>
MyVector<T>::~MyVector()
{
delete [] Array;
}

template<class T>
MyVector<T>& MyVector<T>::operator=(const MyVector<T>& V)
{
int n = V.size;
if(size!=n)
{
delete[] Array;
size = n;
Array = new T[size];
if(Array==NULL)
Error(memoryAllocFail);
}

T* org_Array = Array;
T* new_Array = V.Array;

while(n--)
*org_Array++ = *new_Array++;

return *this;
}

template<class T>
T& MyVector<T>::operator[](int i)
{
if(i<0 || i>=size)
Error(indexOutOfRange);

return Array[i];
}

template<class T>
MyVector<T>::operator T*()
{
return Array;
}

template<class T>
void MyVector<T>::resize(int sz)
{
if(sz<=0)
Error(invalidArraySize);

if(size == sz) return;

int n=(sz<size)?sz:size;

T* org_Array = Array;
T* new_Array = new T[sz]();
if(new_Array==NULL)
Error(memoryAllocFail);

T* tmp = new_Array;
while(n--)
*tmp++ =*org_Array++;
//	*new_Array++ = *org_Array++;  // 这句话无法赋值???原因是啥?

delete[] Array;
Array = new_Array;
size = sz;
}

template<class T>
int MyVector<T>::Size()
{
return size;
}

int main()
{
MyVector<int> V1(5);

for(int i=0; i<V1.Size(); i++)
cin>>V1[i];

MyVector<int> V2 = V1;   // 拷贝构造函数,相当于V2(V1);
MyVector<int> V3;        // 默认构造函数
V3 = V2;  // 复制运算 operator=

MyVector<int> V4(V3);    // 拷贝构造函数;

cout << "V2======\n";
for(int i=0; i<V2.Size(); i++)
cout << V2[i] << " ";
cout << endl;

cout << "V3======\n";
for(int i=0; i<V3.Size(); i++)
cout << V3[i] << " ";
cout << endl;

cout << "V4======\n";
for(int i=0; i<V4.Size(); i++)
cout << V4[i] << " ";
cout << endl;

V1.resize(10);

cout << "================\n";
for(int *p=V1; p<V1+10; p++)
cout << *p << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: