我需要将数据从文件中读取到结构的向量
I need to read data from file into a vector of struct
我希望你们能有所帮助,因为标题说我需要将数据从文件读取到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;
}
因此,myStructA
和myStructB
都必须具有成员whatever
和whatever2
。这可以通过使用myStructA
和myStructB
的普通基类来实现。
相关文章:
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 从只读内存中读取结构
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 读取结构化文件
- CPP 在读取结构数据时无限循环错误?
- 打开文件以读取结构数组
- 无效操作数以二进制读取结构的阵列
- 读取结构数组时出错
- 如何从另一个类读取结构成员
- 读取结构 -- uint32 不命名类型
- 从流或字节中读取结构时遇到问题
- 读取结构C++二进制文件的运行时错误
- 从二进制文件读取结构数据时获取垃圾值
- 在 c++ 中向二进制文件写入/读取结构
- 在C++文件中写入和读取结构体的三维矢量
- C++按字段读取结构,并将结构直接写入流
- 从LISP的套接字中读取c++结构
- 读取结构化二进制文件c++
- C++二进制文件正在读取结构
- 从CArchive保存的二进制数据中读取结构数组