将不同类型的变量添加到向量中
Add different type variables into a vector
我想将数据从文件中读取到不同类型的变量中,并将它们添加到向量中。该文件具有多行,其中相同类型的内容由空格分隔(字符、整数、双精度、双精度、双精度、字符(。我创建了一个类 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;
}
相关文章:
- 有没有办法向这个向量添加元素?
- 这种方式是否可以接受向向量添加unique_ptr?
- 向向量添加元素
- 无法向向量添加回调
- 如何将向量添加到结构中以创建一个库存系统,在该系统中,我可以仅使用一个结构向系统添加多种不同的葡萄酒
- 在一个类中向向量添加元素不适用于其他类
- 以下向 c++ 向量添加元素的方法有什么区别
- 我可以在不推送向量的情况下向向量添加值吗?
- 向向量C++添加对
- 使用单词键将多个行号的向量添加到我的地图中
- 在C++中向指针数组中的向量添加元素
- 要创建一个一开始没有特定维度的类Vector,请在类中创建一个方法,允许向向量添加维度
- 一次向 C++ 向量添加多个元素
- STL - 向存储在 STL 映射中的向量添加值
- 向向量添加向量
- 如何向结构类型的向量添加点
- 为什么我的课'当我向向量添加实例时,会调用s析构函数
- 向c++向量添加新字段
- 在c++中向向量添加对象vs向向量添加指针
- 当Type为unique_ptr时,为向量添加运算符[]