我正在尝试实现一个 insert() 函数,该函数应该将一个值插入一个布尔数组并将等于该值的索引设置为“真”。该IntSet
对象有一个指向value
布尔数组的指针 , 和一个 intsize
来保存数组的大小。因此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;
}
编辑:使用交换将值移动到当前数组。
我希望我的解释足够清楚,如果您需要更多说明,我很乐意提供更多代码。这是一个课堂作业,所以我不期待一个直接的答案,但任何可以为我指明正确方向的东西都会有很大帮助。
谢谢大家!