实现向量调整大小功能时出现bad_alloc错误

Lij*_*hou -1 c++ pointers resize vector bad-alloc

我试图在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; 
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 5

这段代码有几个问题.首先跳出的是:

//increase the capacity to new_size
double *tmp_data = new double(new_size);
Run Code Online (Sandbox Code Playgroud)

您打算分配一个数组,但实际上是分配一个数组double.你的意思是:

double *tmp_data = new double[new_size];
Run Code Online (Sandbox Code Playgroud)

虽然,一旦你解决了......

data = tmp_data;
delete [] data;
Run Code Online (Sandbox Code Playgroud)

你想以相反的顺序做那些,否则你会留下一个被删除的成员.

一旦你解决了这个问题,你就想return早点从你的案例中解决.你有三种情况(不是两种情况,正如你的评论所暗示的那样),你只想在你真正需要的情况下重新分配(即情况#3).在原样,您将在所有情况下重新分配.