简体   繁体   English

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

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

I need to dynamically resize my array by 2 every time it fills up.每次填满时,我都需要将数组的大小动态调整为 2。 It starts with a capacity of 2. This is what I've done (in main.cpp), but it gives me these errors: "warning: deleting array 'test'" and "error: incompatible types in assignment of 'ItemInfo*' to 'ItemInfo [cap]'".它以 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
}

This is the class (in.hpp file):这是 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();

The problem is that you use ItemInfo test[cap];问题是你使用ItemInfo test[cap]; . . Using this declaration results in test being saved on the stack.使用此声明导致test被保存在堆栈中。 Therefore, it has constant size.因此,它具有恒定的大小。 Using temp = new ItemInfo[cap];使用temp = new ItemInfo[cap]; dynamically allocates memory on the heap.在堆上动态分配 memory。 This is the memory which you can also free.这是您也可以免费拨打的 memory。 Thus, test and temp are different types and test cannot be freed.因此, testtemp是不同的类型,无法释放test ItemInfo *test = new ItemInfo[cap]; should work for you.应该为你工作。

Also mind that there is another small mistake: You copy the first cap many values after increasing cap where the old cap should be used.还要注意还有一个小错误:在应该使用旧cap的地方增加cap,您复制了第一个cap的许多值。

You could use realloc too if ItemInfo is trivially copyable so that you do not need the loop to copy the data and temporarily use more memory than maybe needed.如果ItemInfo 可以轻松复制,则您也可以使用realloc ,这样您就不需要循环来复制数据并暂时使用比可能需要的更多的 memory。 The code for using realloc would seem like使用 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));
}

As user4581301 mentioned you could also try to use Vectors if there is nothing specific against it.正如 user4581301 提到的,如果没有什么特别反对的话,您也可以尝试使用Vectors

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

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