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.”
A
vectoris expandable, but only throughpush_back(),resize()and a few other functions – if you useemps[i]andiis greater than or equal to the size of thevector(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 asvector<employee> emps(11);. Otherwise, you should create a temporaryemployeein the loop, read into it, and pass it toemps.push_back().