📄 array.h
字号:
#ifndef __ARRAY_CLASS__
#define __ARRAY_CLASS__
#include <stdexcept>
using namespace std;
template <class T>
class Array
{
protected:
T* data;
unsigned int base;
unsigned int length;
public:
Array();
Array(unsigned int, unsigned int = 0);
~Array();
Array(Array const&);
Array& operator=(Array const&);
T const& operator[](unsigned int) const;
T& operator[](unsigned int);
T* const Data() const;
unsigned int Base() const;
unsigned int Length() const;
void setBase(unsigned int);
void setLength(unsigned int);
};
template <class T>
Array<T>::Array():data(new T[0]),
base(0),
length(0)
{
}
template <class T>
Array<T>::Array(unsigned int n, unsigned int m):
data(new T(n)),
base(m),
length(n)
{
}
template <class T>
Array<T>::Array(Array<T> const &array):
data(new T[array.length]),
base(array.base),
length(array.length)
{
for (unsigned int i = 0; i < length; i++)
data[i] = array.data[i];
}
template <class T>
Array<T>::~Array()
{
if (data != NULL)
delete [] data;
}
template <class T>
T* const Array<T>::Data() const
{return data;}
template <class T>
unsigned int Array<T>::Base() const
{return base;}
template <class T>
unsigned int Array<T>::Length() const
{return length;}
template <class T>
T const& Array<T>::operator[](unsigned int position) const
{
unsigned int offset = position - base;
if (offset >= length)
throw out_of_range("invalid position");
return data[offset];
}
template <class T>
T& Array<T>::operator[](unsigned int position)
{
unsigned int offset = position - base;
if (offset >= length)
throw out_of_range("invalid position");
return data[offset];
}
template <class T>
void Array<T>::setBase(unsigned int newBase)
{base = newBase;}
template <class T>
void Array<T>::setLength(unsigned int newLength)
{
T* const newData = new T[newLength];
unsigned int min = length < newLength ? length : newLength;
for (unsigned int i = 0; i < min; i++)
newData[i] = data[i];
delete [] data;
data = newData;
length = newLength;
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -