Vector of vectors

I'm needing to read in data from a text file in the following format:

Dan Staley 2 1 0 1 2 0 1 2 0 3 4
Sami TahaAbuSnaineh 1 0 1 2 0 1 2 3 1 2 2
Yin Wang 0 1 2 0 1 2 0 2 1 0 1
Matt Field 1 2 0 1 2 0 3 1 1 3 9
Jane Doe 2 0 1 2 0 3 2 1 0 1 2

We were told to use vectors for both the names and the "answers". Here is the thing, the numbers after each name relates to a set of answers from a survey, the vector containing these needs to be a vector of vectors "2D" vector in other words. Say firstnamevector[i] = Dan; lastnamevector[i] = Staley; then the answers out from him should be stored in answers[i][0-10]. Problem is I can't figure out how to read all this in, the vectors I have for the names work fine if there are no numbers after them, but I can't get it to store the numbers correctly. I've provided the code below that I am trying. Any help will be greatly appreaciated!



fstream inFile;

inFile.open("testingDB.txt");

string first;
string last;

int i = 0;

int numba;

vector <string> lastName;
vector <string> firstName;
vector <vector <int> > answers;

while (inFile)
{
inFile >> first >> last;
firstName.push_back(first);
lastName.push_back(last);

for (int j = 0; j < 11; j++)
{
inFile >> numba;
answers.push_back(numba);
}

i++;
}

inFile.close();
well, the first thing I notice is that you are trying to push number int numba into answers. that is not going to work, you should push vectors there. if you really want to do it this way, well you depend on what your sick lecturer tells you, you need to first push numbers into some vector<int>, and then push it to your answers.
But if I were you I would create a class to hold a name and vector of answers, and then push that into some vector. Otherwise it is always a bad idea to use vector<vector<some_type>>, it is inefficient.

And also if you declare variables closer to where they are actually used, your program would become more readable and safe.

btw, veeery politically correct names in example. :)
Last edited on
Yea my instructor is requiring that the vector of vectors is to be called as vector< vector<int> > answers; I know I've seen several examples where this isn't the way this should be allocated, but for purposes of grading, I need to stick within specifications. I did get it to work, thanks.

Oh and the names, this is just a sample program I made to test this function only, it isn't the way it will look in the actual program, I'm much more organized, this is only one function that needed to work. The rest of the actual program, sorts answers from individuals, compares them to others, who answered the same, the question they thought most important, and then outputs the 10 best matches.
Topic archived. No new replies allowed.