我想用数组实现一个类。如果数组的大小被破坏,我会调用resize()函数。但是我似乎无法将动态数组编码为数据成员。有人可以指导我如何解决这个问题吗?
这是我到目前为止所得到的:
class ArrayList
{
public:
ArrayList()
{
array[ARR_SIZE] = {0};
space = 0;
size = ARR_SIZE;
}
void insert(int place, int value)
{
if (place >= size)
cout << "Sorry, that index is not accessible" << endl;
else
{
array[place] = value;
space++;
if(space == size)
allocate();
}
}
void remove(int place)
{
if(place >= size)
cout << "Sorry, that index is not accessible" << endl;
else
{
array[place] = NULL;
space--;
}
}
void allocate()
{
int* array = new int[size*2];
size = size*2;
}
int usedSize()
{
return space;
}
int totalSize()
{
return size;
}
private:
int array[ARR_SIZE];
int space;
int size;
};
答案 0 :(得分:7)
使用std::vector
。 C ++不支持类或其他类型的可变长度或动态大小的数组。
答案 1 :(得分:4)
使用std::vector
并让它为您管理所有内容:
#include <vector>
class ArrayList
{
public:
ArrayList()
{
array.reserve(ARR_SIZE);
}
void insert(int place, int value)
{
if ((place < 0) || (place > array.size()))
std::cout << "Sorry, that index is not accessible" << std::endl;
else
array.insert(array.begin()+place, value);
}
void remove(int place)
{
if ((place < 0) || (place >= array.size()))
std::cout << "Sorry, that index is not accessible" << std::endl;
else
array.erase(array.begin()+place);
}
int usedSize()
{
return array.size();
}
int totalSize()
{
return array.capacity();
}
private:
std::vector<int> array;
};
如果你真的想自己管理阵列内存,那么你做错了。试试这个:
class ArrayList
{
public:
ArrayList()
{
array = new int[ARR_SIZE];
space = 0;
size = ARR_SIZE;
}
ArrayList(const ArrayList &src)
{
array = new int[src.size];
space = src.space;
size = src.size;
for(int i = 0; i < space; ++i)
array[i] = src.array[i];
}
~ArrayList()
{
delete[] array;
}
void insert(int place, int value)
{
if ((place < 0) || (place > space))
std::cout << "Sorry, that index is not accessible" << std::endl;
else
{
if (space == size)
allocate();
for(int i = space-1; i > place; --i)
array[i] = array[i-1];
array[place] = value;
++space;
}
}
void remove(int place)
{
if ((place < 0) || (place >= space))
std::cout << "Sorry, that index is not accessible" << std::endl;
else
{
for(int i = place+1; i < space; ++i)
array[i-1] = array[i];
--space;
}
}
void allocate()
{
int* newarray = new int[size*2];
for (int i = 0; i < space; ++i)
newarray[i] = array[i];
delete[] array;
array = newarray;
size *= 2;
}
int usedSize()
{
return space;
}
int totalSize()
{
return size;
}
ArrayList& operator=(const ArrayList &src)
{
int *newarray = new int[src.size];
for(int i = 0; i < src.space; ++i)
newarray[i] = src.array[i];
delete[] array;
array = newarray;
space = src.space;
size = src.size;
return *this;
}
private:
int *array;
int space;
int size;
};
答案 2 :(得分:1)
我还没有给你发表评论的声誉,但你有没有试过C ++的std::vector
?它完全符合您的要求:
答案 3 :(得分:0)