动态数组删除旧指针并将其设置为新数组C++

Dynamic Array deleting old pointer and setting it to new array C++

本文关键字:数组 新数组 C++ 设置 删除 指针 动态      更新时间:2023-10-16

我正在尝试实现一个insert()函数,该函数应该将一个值插入布尔数组并将等于该值的索引设置为"true"。IntSet对象有一个指向布尔数组的指针value和一个用于保存数组大小的整数size。因此,IntSet A(2, 4, 10);将创建一个大小为 10 的数组,并将 2、4、10 处的索引设置为 true。

insert() 函数返回 true 或 false,具体取决于它是否插入了值,如果插入的值大于数组的大小,它应该调整数组的大小。因此,A.insert(1000);会将数组大小调整为 1001,并将索引 1000 处的值设置为 true。

我的问题是删除旧的数组指针并将其设置为新的、调整大小的数组。无论我做什么,它总是在删除[]处中断,我不知道为什么。

这是我到目前为止所拥有的:

bool IntSet::insert(int toInsert) {
int tempSize = this->size;
// if toInsert is greater than the number of elements in the array, call 
// copy constructor and assign new value to true
if(toInsert < this->size && toInsert >= 0) {
    value[toInsert] = true;
    return true;
}
IntSet largerSet(toInsert+1);
if(toInsert > this->size+1) {

    for(int i = 0; i < largerSet.size+1; i++) {
        largerSet.value[i] = false;
    }
    largerSet.value[toInsert] = true;
    for(int i = 0; i < tempSize+1; i++) {
        if(this->value[i] != false) {
            largerSet.value[i] = true;
        }
    }
    std::swap(value, largerSet.value);
    std::swap(size, largerSet.size);
}
return true;
}

编辑:使用交换将值移动到当前数组。

我希望我的解释足够清楚,如果您需要更多澄清,我很乐意提供更多代码。这是针对课堂作业的,所以我不期待直接的答案,但任何能为我指明正确方向的东西都会有很大帮助。

谢谢大家!

您应该将分配留给构造函数,将解除分配留给析构函数,将副本留给复制构造函数和复制赋值运算符。您现在有一个函数可以执行所有操作。

重新分配的一个干净方法是首先提供一个swap函数(交换你的指针+大小);鉴于此,创建一个新大小的临时函数(如largerSet),初始化新数据,然后用largerSet交换你的集合。当临时超出范围时,它会被销毁,并自动调用delete[]

现在,当largerSet超出范围时,largerSet.value被删除(我假设这是在您的析构函数中完成的),但现在这等于value,所以您的数据消失了。