C++ 使动态数组变大
这是一个非分级的挑战问题,我希望尽快找到尽可能多的素数。其中一个限制是我必须使用new/delete,所以C++ 使动态数组变大,c++,arrays,dynamic,primes,C++,Arrays,Dynamic,Primes,这是一个非分级的挑战问题,我希望尽快找到尽可能多的素数。其中一个限制是我必须使用new/delete,所以std::vector不是一个选项。在这个问题中,我需要添加一个数组(在我的例子中是一个动态创建的名为list的数组)来保存素数。我的目标是实现与vector类似的功能,在vector中,仅当当前阵列中没有足够的空间时,才需要分配新内存,并且当当前阵列使用分配长度的2倍填充新阵列时,才需要分配新内存。下面是我在列表中添加素数的函数 void PrimeList::addPrimeToList
std::vector
不是一个选项。在这个问题中,我需要添加一个数组(在我的例子中是一个动态创建的名为list的数组)来保存素数。我的目标是实现与vector类似的功能,在vector中,仅当当前阵列中没有足够的空间时,才需要分配新内存,并且当当前阵列使用分配长度的2倍填充新阵列时,才需要分配新内存。下面是我在列表中添加素数的函数
void PrimeList::addPrimeToList(int newPrime) {
if( sizeof(list)/sizeof(int) > total ) { // there is still room in the array
list[total++] = newPrime;
} else { // list has run out of space to put values into
int *newList = new int [total*2]; // new list to hold all previous primes and new prime
for(int i=0; i < total; i++) { // for every old prime
newList[i] = list[i]; // add that old prime to the new list
}
newList[total++] = newPrime; // set largest and the last index of the new list to the new prime
delete [] list; // get rid of the old list
list = newList; // point the private data member list to the newly created list.
}
}
void PrimeList::addPrimeToList(int-newPrime){
如果(sizeof(list)/sizeof(int)>total){//数组中还有空间
列表[total++]=newPrime;
}else{//list已耗尽空间,无法将值放入其中
int*newList=newint[total*2];//保存所有先前素数和新素数的新列表
对于(int i=0;i
注意:total是一个私有数据成员,它保存到目前为止找到的素数数量
我的问题是else语句(以及耗时的分配/解除分配)在每次调用函数时都会发生(前两次调用总是运行if的第一部分除外)。我认为if部分在绝大多数时间都会运行—只要列表还有空间—那么为什么不呢?发生这种情况的原因是用于数组大小的表达式,即
sizeof(list)/sizeof(int)
是一个常量表达式。它的值不依赖于列表
指针指向的已分配数组
您需要单独存储分配的大小以使此代码正常工作:
if( allocatedSize > total ) { // there is still room in the array
list[total++] = newPrime;
} else { // list has run out of space to put values into
int *newList = new int [total*2]; // new list to hold all previous primes and new prime
allocatedSize *= 2;
for(int i=0; i < total; i++) { // for every old prime
newList[i] = list[i]; // add that old prime to the new list
}
newList[total++] = newPrime; // set largest and the last index of the new list to the new prime
delete [] list; // get rid of the old list
list = newList; // point the private data member list to the newly created list.
}
如果(allocatedSize>total){//阵列中仍有空间
列表[total++]=newPrime;
}else{//list已耗尽空间,无法将值放入其中
int*newList=newint[total*2];//保存所有先前素数和新素数的新列表
allocatedSize*=2;
对于(int i=0;i