Viki Liu
Viki Liu

Reputation: 112

Add different type variables into a vector

I want to read data from a file into different types of variables and add them to a vector. The file has multiple lines with the same type of content separated by spaces (char, int, double, double, double, char). I created a class Atom:

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

And my main function looks like that:

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);
  }
}

The error "main.cpp:38:12: error: no matching member function for call to 'push_back' Inputs.push_back(name, fixed, x_c, y_c, z_c, repr);

Am I have to somehow override push_back function for multiple variables to be pushed?

Upvotes: 0

Views: 255

Answers (2)

Yunfei Chen
Yunfei Chen

Reputation: 626

The problem is that your vector expects an Atom object not a list of parameters, create an object of atom first and intialize its parameters, so to start off create a constructor in your header file, so that you have something that looks like the following:

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

After this in your main file create an object of Atom and push it into your vector by calling the constructor.

Upvotes: 2

Rohan Bari
Rohan Bari

Reputation: 7726

Use a struct if you just want to store variables in a group. Also, you need to pass an instance of Atom not its members to the vector.

Another problem is that the class you've defined has private members which is inaccessible anywhere in your code except the class itself. It has not a single member function to obtain their values, that's the reason of using struct here, its variables are visible anywhere, just need to be followed by a . (e.g. atom.name access name character array).

Do something like:

#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;
}

Upvotes: 1

Related Questions