我需要实现 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;
 }

该程序正确编译,没有错误,但确实给了我错误分段错误

注意:最主要的是,我需要学习如何使用调整大小功能来调整动态成员数据容量的帮助。另外,我知道 vector 在这种情况下会有所帮助,但是我们仍然不允许使用

这是教授的特殊要求:
>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/>

最佳答案

当您由于resize而成为add时,您将used递增两次。

bool IntSet::add(int anInt)
{
    if (contains(anInt) == false)
    {
       if (used >= capacity)
          resize(used++);  // Here And this is a post increment.
                           // resize will be called with used before the increment
                           // so you will wind up asking for a buffer the same size.

       data[used++] = anInt; // and here.

       return true;
    }
    return false;
}

所以什么都没用。您跳过一个空格并在其后写入该空格。再加上resize(used++);并不需要更多空间,因此您实际上在分配的存储区之外写入了两个位置,这可能会触发段错误。



您不想在resize(used++);处增加任何内容。您想将一个添加到capacity,但不增加它,所以
resize(capacity +1);

看起来不错。但是,指令要求的内容更像是:
int newcap = capacity * 1.5;
if (newcap == capacity) // newcap didn't change. eg: 1*1.5 = 1
{
    newcap ++;
}
resize(newcap);

虽然这是蛮力。有更聪明的方法可以做到这一点。

关于c++ - 如何在C++中实现resize()以更改动态成员数据的容量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46397442/

10-11 22:09