我需要实现函数resize() :
void IntSet::resize(int new_capacity)
{
if (new_capacity < used)
new_capacity = used;
if (used == 0)
new_capacity = 1;
capacity = new_capacity;
int * newData = new int[capacity];
for (int i = 0; i < used; ++i)
newData[i] = data[i];
delete [] data;
data = newData;
}
函数内部:
IntSet IntSet::unionWith(const IntSet& otherIntSet) const
{
IntSet unionSet = otherIntSet;
for (int i = 0; i < used; i++)
{
if (unionSet.contains(data[i]))
unionSet.add(data[i]);
}
return unionSet;
}
还有这个:( 注意:我已经在 add() 函数中找到了它,但我认为它不正确)
bool IntSet::add(int anInt)
{
if (contains(anInt) == false)
{
if (used >= capacity)
resize(used++);
data[used++] = anInt;
return true;
}
return false;
}
该程序可以正确编译而没有错误,但它确实给了我一个 Segmentation fault的错误
注意:主要是我需要帮助来学习如何使用 resize 函数来调整动态成员数据的容量。另外,我知道向量在这种情况下会有所帮助,但我们还不允许使用向量
以下是教授的特殊要求:
>Special Requirement (You will lose points if you don't observe this.) <br/>
>When calling resize *(while implementing some of the member functions)* to
>increase the capacity of the dynamic arrays, use the following resizing
>rule (unless the new capacity has to be something else higher as dictated
>by other >overriding factors): <br/>
>
>*"new capacity" is "roughly 1.5 x old capacity" and at least "old capacity
> + 1".* <br/>
>
>The latter *(at least " old capacity + 1 ")* is a simple way to take care
>of the subtle case where " 1.5 x old capacity " evaluates (with truncation)
>to the >same as "old capacity". <br/>