BAD_ALLOC错误实现向量调整大小函数时

bad_alloc error when implementing vector resize function

本文关键字:函数 调整 向量 ALLOC 错误 实现 BAD      更新时间:2023-10-16

我正在尝试在C 中实现Vector::resize()功能。我认为我处理了每种情况,但仍然会遇到bad_alloc错误。此调整大小实施中的三种情况:

  1. new_size小于old_size时(在我的代码中,size);
  2. new_size大于size,但小于容量;
  3. new_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 elements
    //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; 
}

此代码有几件事。首先跳出的一个是:

//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),您只想重新分配。根据,您在所有情况下都重新分配。

正如巴里指出的那样,您有一些错误。

这是您的代码,有一些建议:

void Vector::resize(int new_size)
{
    if(new_size <= size) {     // use "<=" here
        // if you are dealing with doubles, what is there to erase?
        // (I would remove that loop)
        for(int i = size-1; i > new_size; i--){
            erase(i);
        }
        size = new_size;
        return;   // you're done here, you can return
    }
    
    if(new_size <= capacity) {    // again "<=", if you return, then no need for anything more
        // "insert()" sounds confusing, you're doing a set() here
        for(int i=size; i < new_size; i++){
            insert(i, 0.0);
        }
        size = new_size;
        return;   // again, you can now return, you're done
    }
    
    double *tmp_data = new double(new_size);
    
    // you could use std::copy() here
    for(int i=0; i < size; i++)
    {
        tmp_data[i] = data[i];
    }
    
    // as indicated by Barry, you could inverse these
    delete [] data;
    data = tmp_data;
    
    size = new_size;
    capacity = new_size; 
}

我删除了您的所有评论,并为您仔细阅读。

另一种处理3个案例的方法是使用Else关键字这样:

if(new_size <= size) {
    ...
} else if(new_size <= capacity) {
    ...
} else {
    ...
}

,要明确说明,您可以从每个...案例中拨打三个子函数。这样,您可以看到resize()函数的主要逻辑。