在一个文件中循环一次,将行读取到添加到数组中的对象中

Loop through a file once, reading lines into objects added to an array

本文关键字:添加 读取 对象 数组 一个 文件 循环 一次      更新时间:2023-10-16

我正在阅读一个文件,其中的每一行都代表我将添加到数组中的对象。我事先不知道文件中有多少行,只能循环浏览一次。此外,我被限制使用普通数组,没有其他容器或集合类。这是我得到的:

ifstream f;
f.open("lines.csv");
string line;
string theCode;
string theName;
Manufacturer **manufacturers = new Manufacturer*[752]; // this number can't be here - I have to allocate dynamically
int index = 0;
while(getline(f, line))
{
    theCode = line.substr(0, 6);
    theName = line.substr(7, string::npos);
    Manufacturer* theManufacturer = new Manufacturer(atoi(theCode.c_str()), theName);
    manufacturers[index++] = theManufacturer;
}

每次索引到达当前数组的末尾时,都需要重新分配一个更宽的数组。就像这样。

int capacity = 752;
while(getline(f, line))
{
    if (capacity <= index) {
        capacity = (capacity+1) * 2;
        Manufacturer **tmp = new Manufacturer*[capacity];
        std::copy(manufacturers, manufacturers+index, tmp);
        delete[] manufacturers;
        manufacturers = tmp;
    }
    /* ... */;
}