我需要将数据从文件中读取到结构的向量

I need to read data from file into a vector of struct

本文关键字:读取 结构 向量 文件 数据      更新时间:2023-10-16

我希望你们能有所帮助,因为标题说我需要将数据从文件读取到struct的向量,但是我需要使用readfile函数在不同时间读取不同的结构。它是困惑我的for循环

for(temp; getline(infile, temp.whatever) && getline(infile, temp.whatever2); i++)
    structname.pushback(temp);

这将功能与单个结构联系起来。编写另一个功能以在其他结构中读取的功能有点反对。显然,这有效,但是有一种方法可以使其更加重复使用。预先感谢

是的,您可以做一些使代码可用于不同结构类型的代码。

但是,所有结构类型必须在功能内使用了字段。

看起来像这样:

template<typename T>
void readData(vector<T>& v, istream& infile)
{
    T temp;
    while(getline(infile, temp.whatever) && getline(infile, temp.whatever2))
    {
        v.push_back(temp);
    }
}
int main() {
    // Add code for infileA and infileB
    vector<myStructA> va;
    readData(va, infileA);  // or readData<myStructA>(va, infileA); if you prefer
    vector<myStructB> vb;
    readData(vb, infileB);  // or readData<myStructB>(vb, infileB); if you prefer
    ....
    ....
    return 0;
}

因此,myStructAmyStructB都必须具有成员whateverwhatever2。这可以通过使用myStructAmyStructB的普通基类来实现。