小编Lij*_*hou的帖子

实现向量调整大小功能时出现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 && …
Run Code Online (Sandbox Code Playgroud)

c++ pointers resize vector bad-alloc

-1
推荐指数
1
解决办法
523
查看次数

标签 统计

bad-alloc ×1

c++ ×1

pointers ×1

resize ×1

vector ×1