C++ 如何使用相同的类和方法来读取/写入可变大小的数据

C++ How to use same class and methods for reading/writing variable size data

本文关键字:数据 读取 何使用 方法 C++      更新时间:2023-10-16

我写了一个具有读写方法的c ++类。这些方法从 csv 文件读取和写入行。 目前,我已经实现了对具有五个元组(列)的csv文件的读写,例如 - EmpNo,EmpName,地址,部门,经理。 类包含这 5 个元组作为类的成员变量。

所以基本上,在 read() 中,我使用 fstream 读取行并将元组值放入相应的成员变量中。同样,对于写入,我将行数据从用户获取到类成员变量中,并将其写入 csv 文件中。

现在我想使用相同的代码来读取和写入另一个 csv 文件,该文件在上述五个元组中只有两个元组 - EmpNo、EmpName。

我可以考虑维护一个变量来识别我正在读取/写入的 CSV,并相应地在所有代码中都有 if/else。但这看起来并不干净。 使用我的方法用于 read() 的伪代码如下:

read()
{
read EmpNo;
read EmpName;
If (csv_with_5_tuple == true)
{
read Address;
read Department;
read Manager;
}
}
//Here, 'csv_with_5_tuple ' will be set when reading/writing from/to csv file of five tuples.

使用这种方法,我需要在课堂上的任何地方添加"if"条件。

谁能建议我在 c++ 中做到这一点的最佳方法?

你可以为此使用类继承。有伪代码演示了这个想法:

class csv2 {
public:
virtual void read()
{
read EmpNo;
read EmpName;
}
};
class csv5 : public csv2
{
public:
virtual void read()
{
csv2::read();
read Address;
read Department;
read Manager;
}
};

通过使用一些vector和模板,您可以执行以下操作:

template <typename T>
std::vector<T> csv_read(std::istream& is, const std::vector<std::string T::*>& members)
{
std::vector<T> res;
std::string header;
std::getline(is, header);
while (true) {
T obj;
for (auto m : members) {
is >> obj.*m;
}
if (!is) {
break;   
}
res.push_back(obj);
}
return res;
}

用法类似于

const std::vector<std::string Person2::*> members = {&Person2::Name, &Person2::AgeStr};
auto persons = csv_read<Person2>(ss, members);

演示

或者更简单,如果你只使用std::vector<std::vector<std::string>>

std::vector<std::vector<std::string>> csv_read(std::istream& is, std::size_t rowCount)
{
std::vector<std::vector<std::string>> res;
std::string header;
std::getline(is, header);
while (true) {
std::vector<std::string> row(rowCount);
for (auto& col : row) {
is >> col;
}
if (!is) {
break;   
}
res.push_back(row);
}
return res;
}

用法类似于

auto data = csv_read(ss, 2);

演示