如何实现resize()来改变c ++中动态成员数据的容量

时间:2017-09-25 04:04:19

标签: c++ class dynamic-memory-allocation helper-functions dynamic-class

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

程序正确编译没有错误,但它确实给我一个错误 分段错误

注意:主要的是我需要帮助学习如何使用resize函数来调整动态成员数据的 capacity 。此外,我知道矢量在这种情况下会有所帮助,但我们不允许使用矢量

以下是教授的特殊要求

>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/>

1 个答案:

答案 0 :(得分:2)

由于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);

看起来正确。但是,指令所要求的更像是:

[Serializable]
public class A
{
    public int i;
    public string j;
    public B b;
}

[Serializable]
public class B
{
    public int k;
    public string l;
}

A a = new A();
a.b.k = 0;

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