将不同类型的变量添加到向量中

Add different type variables into a vector

本文关键字:向量 添加 变量 同类型      更新时间:2023-10-16

我想将数据从文件中读取到不同类型的变量中,并将它们添加到向量中。该文件具有多行,其中相同类型的内容由空格分隔(字符、整数、双精度、双精度、双精度、字符(。我创建了一个类 Atom:

class Atom {
private:
char Atom_Name;
int Fixed;
double X_cord;
double Y_cord;
double Z_cord;
char Represent;
};

我的主要功能看起来像这样:

ifstream inFS;
string line;
string FileName = "File_Name.txt";
inFS.open(FileName);  
// Verify file opened correctly.
// Output error message and return 1 if file stream did not open correctly.
if (!inFS.is_open()) {
cout << "Error opening " << FileName << endl;
exit(1);
}
vector<Atom> Inputs;
while (getline(inFS, line)){
istringstream ss(line);
char name;
int fixed;
double x_c, y_c, z_c;
char repr;
ss >> name >> fixed >> x_c >> y_c >> z_c >> repr;
for (int i = 0; i<704; i++){
Inputs.push_back(name, fixed, x_c, y_c, z_c, repr);
}
}

错误"main.cpp:38:12:错误:没有匹配的成员函数来调用"push_back" Inputs.push_back(名称、固定、x_c、y_c、z_c、repr(;

我是否必须以某种方式覆盖push_back函数才能推送多个变量?

问题是你的向量需要一个 Atom 对象而不是参数列表,首先创建一个 atom 对象并初始化它的参数,所以首先在你的头文件中创建一个构造函数,这样你就有如下所示的东西:

Atom::Atom(char name, int fixed, double x, double y, double z){
this->name = name;
this->fixed = fixed;
this->x = x;
this->y = y;
};

之后,在您的主文件中创建一个 Atom 对象,并通过调用构造函数将其推送到您的向量中。

如果您只想将变量存储在组中,请使用struct。此外,您需要将Atom而不是其成员的实例传递给向量。

另一个问题是,您定义的类具有私有成员,除了类本身之外,该成员在代码中的任何地方都无法访问。它没有一个成员函数来获取它们的值,这就是在这里使用struct的原因,它的变量在任何地方都可见,只需要后跟一个.(例如atom.name访问name字符数组(。

执行以下操作:

#include <vector>
struct Atom {
char name[50]; // define the char array length too
...
};
int main(void) {
Atom atom; // to push_back()
std::vector<Atom> vecAtom;
.
std::cin >> atom.name >> ...;
.
vecAtom.push_back(atom); // passing a struct of `Atom` here
.
.
return 0;
}