c++ - 将动态分配的指针数组调整为类

标签 c++ class dynamic-memory-allocation

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

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 

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

       ++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++;
}

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

最佳答案

您不能调整数组的大小,您只能分配新的(具有更大的大小)并复制旧数组的内容。如果您不想使用 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;
}

关于c++ - 将动态分配的指针数组调整为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39437153/

相关文章:

c++ - Ostream tellp 在 Windows 上失败但在 Linux 上没有

c++ - 为什么在释放由 apriltags image_u8_create() 分配并存储在 C++ 指针的 2D vector 中的内存时出现错误?

c - 如何在 C 中动态分配二维数组?

C++解构指针数组

c++ - boost::uuids::random_generator 线程安全吗?

C++ 指针名称

java - 如何在 iOS 上的 Turbo 模块中发出事件

java - 类 unix 权限对象的类名

java - 第一次请求的 servlet 响应时间很慢

Java - 类和方法的问题