将动态分配的指针数组调整为类的大小

Arc*_*gel 1 c++ class dynamic-memory-allocation

在不使用向量的情况下如何调整数组大小?我要调整大小的数组是一个指向类的指针

class A
{
    private:
    B * b;
    int numOfItems;
    int maxNumOfItems;

    public:
    A();
    ~A();
    resizeMX();
};


A::A()
{
     numOfItems = 0;
     maxNumOfItems = 20;
     b = new B[maxNumOfItems];
     for(int i=0;i<maxNumOfItems ;i++)
     {
         b[i] = 0;
     }
}

A::~A()
{
    for(int i=0;i<numOfItems;i++)
     {
         delete [] b;
     }
}

void A::resizeMX(const B & obj)
{
     bool value=false;
     if(numOfItems<=maxNumOfItems && value == false)
     {
        //assign values to *b in for loop
     }
     else
     {
       //resize index of *b 
Run Code Online (Sandbox Code Playgroud)

我知道我们应该动态分配新的内存。像这样吗

       ++maxNumOfItems; 
        b=new B[maxNumOfItems];
        //keep previous assigned values and add new values at the end
        for(int j=numOfItems;j<maxNumOfItems;j++)
        {
            //assign values to b[j]
        }
     }  
        numOfItems++;
}
Run Code Online (Sandbox Code Playgroud)

假设我确实重载了=运算符

小智 5

您无法调整数组的大小,只能分配新数组(具有更大的大小)并复制旧数组的内容。如果您不想使用std :: vector(出于某种原因),请使用以下代码:

int size = 10;
int* arr = new int[size];

void resize() {
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}
Run Code Online (Sandbox Code Playgroud)