繁体   English   中英

我需要动态调整对象数组的大小

[英]I need to dynamically resize an array of objects

每次填满时,我都需要将数组的大小动态调整为 2。 它以 2 的容量开始。这就是我所做的(在 main.cpp 中),但它给了我这些错误:“警告:删除数组'test'”和“错误:'ItemInfo * 分配中的不兼容类型” ' 到 'ItemInfo [cap]'”。

ItemInfo test[cap];

//I have code here to open file, read from file, etc

if(itemCount >= cap){
    cap += 2;
    ItemInfo *temp;
    temp = new ItemInfo[cap];
    for(int i = 0; i < cap; i++){
        temp[i] = test[i];
    }
    delete[] test; //error here
    test = temp;   //error here
}

这是 class(in.hpp 文件):

#include <iostream>
#include <iomanip>

using namespace std;

class ItemInfo {
private:
    int itemId;
    char description[40];
    double manCost;
    double sellPrice;
public:
    ItemInfo() {
        itemId = 0;
        *description = '\0';
        manCost = 0.0;
        sellPrice = 0.0;
    }
    void setItemId(const char *num);
    void setDescription(const char *cstr);
    void setManCost(const char *num);
    void setSellPrice(const char *num);
    int getItemId();
    const char *getDescription();
    double getManCost();
    double getSellPrice();

问题是你使用ItemInfo test[cap]; . 使用此声明导致test被保存在堆栈中。 因此,它具有恒定的大小。 使用temp = new ItemInfo[cap]; 在堆上动态分配 memory。 这是您也可以免费拨打的 memory。 因此, testtemp是不同的类型,无法释放test ItemInfo *test = new ItemInfo[cap]; 应该为你工作。

还要注意还有一个小错误:在应该使用旧cap的地方增加cap,您复制了第一个cap的许多值。

如果ItemInfo 可以轻松复制,则您也可以使用realloc ,这样您就不需要循环来复制数据并暂时使用比可能需要的更多的 memory。 使用 realloc 的代码看起来像

ItemInfo *test = (*ItemInfo) malloc(cap * sizeof(ItemInfo));
// use malloc here as realloc and new should not be mixed
[...]
if(itemCount >= cap){
    cap += 2;
    test = (*ItemInfo) realloc(test, cap * sizeof(ItemInfo));
}

正如 user4581301 提到的,如果没有什么特别反对的话,您也可以尝试使用Vectors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM