Loading data into a vector of structures

2020-02-02 01:51发布

问题:

I am trying to load some data from a text file into a vector of structures. My question is, how do you indicate the size of the vector? Or should I be using a the vector push_back function to do this dynamically, and if so, how does this work when populating a structure?

The full program is outlined below:

My structure is defined as

struct employee{
    string name;
    int id;
    double salary;
};

and the text file (data.txt) contains 11 entries in the following format:

Mike Tuff
1005 57889.9

where "Mike Tuff" is the name, "1005" is the id, and "57889.9" is the salary.

I am trying to load the data into a vector of structs using the following code:

#include "Employee.h" //employee structure defined in header file

using namespace std;

vector<employee>emps; //global vector 

// load data into a global vector of employees.
void loadData(string filename)
{
    int i = 0;
    ifstream fileIn;
    fileIn.open(filename.c_str());

    if( ! fileIn )  // if the bool value of fileIn is false
         cout << "The input file did not open.";

    while(fileIn)
    {
        fileIn >> emps[i].name >>emps[i].id >> emps[i].salary ;
        i++;
    }

    return;
}

When I execute this, I get an error that says: "Debug Assertion Failed! Expression: vector subscript out of range."

回答1:

A vector is expandable, but only through push_back(), resize() and a few other functions - if you use emps[i] and i is greater than or equal to the size of the vector (which is initially 0), the program will crash (if you're lucky) or produce weird results. If you know the desired size in advance, you can call e.g. emps.resize(11) or declare it as vector<employee> emps(11);. Otherwise, you should create a temporary employee in the loop, read into it, and pass it to emps.push_back().



回答2:

std::istream & operator >> operator(std::istream & in, employee & e)
{
  return in >> e.name >> e.id >> e.salary; // double not make good monetary datatype.
}

int main()
{
  std::vector<employee> emp;
  std::copy(std::istream_iterator<employee>(std::cin), std::istream_iterator<employee>(), std::back_inserter(emp));
}