我正在尝试在C ++中实现向量调整大小功能。我想我处理了每种情况但仍然出现bad_alloc错误。此调整大小实现中的三种情况:1)当new_size小于old_size时(在我的代码中,大小); 2)当new_size大于但小于容量时; 3)案例3:当新的_size大于容量时
void Vector::resize(int new_size)
{
//if the new_size is smaller, make the size smaller, don't need to worry about memory
//the content is reduced to its first n element
//remove those beyond and destroy them
if(new_size < size){
for(int i = size-1; i > new_size; i--){
erase(i);
}
size = new_size;
}
//if the new_size is bigger
//case 1: new_size is smaller than capacity
//inserting at the end of as many elements as needed
if(new_size > size && new_size < capacity){
for(int i=size; i < new_size; i++){
insert(i, 0.0);
}
size = new_size;
}
//case 2: new_size is greater than capacity
//increase the capacity of the container
//increase the capacity to new_size
double *tmp_data = new double(new_size);
//transfer data to tmp_data
for(int i=0; i < size; i++)
{
tmp_data[i] = data[i];
}
data = tmp_data;
delete [] data;
size = new_size;
capacity = new_size;
}
答案 0 :(得分:5)
此代码有几个问题。首先跳出的是:
//increase the capacity to new_size
double *tmp_data = new double(new_size);
您打算分配一个数组,但实际上是在分配一个double
。你的意思是:
double *tmp_data = new double[new_size];
虽然,一旦你解决了......
data = tmp_data;
delete [] data;
您希望以相反的顺序执行这些操作,否则您将自己留下已删除的成员。
一旦你修复那个,你就想早点return
从你的案件中找到。您有三种情况(不是两种,正如您的意见所暗示的那样),并且您只想在您确实需要的情况下重新分配(即情况#3)。在原样,您将在所有情况下重新分配。