Hi I'm fairly new to vectors in C++ and I'm having some problems with them. I have a vector of vectors but I don't know why it is causing a segment fault in my program?

vector < vector<int> > grades;
int temp;
for(int i = 0; i < 30; i++)
{
     for(int j = 0; j < 20; j++)
     {
            myGrades>>temp;
            grades[i].push_back(temp);
      }
}

What can I do to get this to work? It compiles fine but then crashes when I try to run it... I've debugged it down to these lines of code. Please help!

your vector has no reserved sizes, so all insertions

//option 1
	vector < vector<int> > grades;
	for(int i = 0; i < 30; i++)
	{
		vector<int> tempVec;
		for(int j = 0; j < 20; j++)
		{
			int temp;
                        myGrades>>temp;
			
                        tempVec.push_back( temp );
		}
		grades.push_back( tempVec );
	}
//option 2
	vector < vector<int> > grades( 30 );
	for(int i = 0; i < 30; i++)
	{
		grades[i].resize(20);
		for(int j = 0; j < 20; j++)
		{
			int temp;
                        myGrades>>temp;			
                        grades[i][j] = temp;
		}
	}

t

But why do you need vector of vectors ?

Thanks Kux! Well I mainly wanted to try to use them to learn more about them... I know an array might work a little better for my program but I figured why not learn :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.