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

标签 c++ arrays dynamic-memory-allocation

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

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

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

这是我目前所拥有的:

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,所以你的数据不见了。

关于c++ - 动态数组删除旧指针并将其设置为新数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416200/

相关文章:

c++ - clang 在 Coliru 中编译此代码段,但不在 Compiler Explorer 中编译。为什么?

c++ - 拖动窗口时如何覆盖默认的 linux Alt+鼠标行为?

c++ - C not运算符应用于int?

c - 在另一个函数中使用创建结构函数会关闭程序。有小费吗?

c++指针赋值运算符重载(不仅是对象赋值,还有指针赋值)

java - 遍历数组列表的时间复杂度

Java 多维数组

python - 识别点并返回该点的值,保留最高值作为引用

c++ - 谁定义了新的运算符?

无法从二维动态数组中释放内存