Vector subscript out of range

Hi guys.My project's goal is to read some numbers from input file,then create a grid.
my input file is:
2 3
3 4 5
1 2 4
first line is rows and colums.second and third line the grid location values.
Please help me.??
My code is

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include<vector>
using namespace std;

int rows,cols;
vector< vector<int> > grid(rows, vector<int>(cols));


void read()
{
ifstream reader("input.txt");

reader >> rows;
reader >>cols;
int value;
reader >>value;
for ( int i=0; i<rows; i++)
{
for ( int j=0; j<cols;j++)
{
grid[i][j]=value;
reader>>value;
}
}


}

void write()
{
ofstream output_file ("out.txt");

output_file <<grid[2][3];

output_file.close();


}
int main( int argc, char* argv[])
{
read();

write();

return 0;
}
1
2
int rows,cols;
vector< vector<int> > grid(rows, vector<int>(cols));

Do you realise that rows and cols are zero when this global code is run?
closed account (N36fSL3A)
No, they're of undefined size.
how can I fix this problem??
closed account (N36fSL3A)
initialize the two variables.
No, they're of undefined size.
Global POD types are given value zero. They are initialised and the code is deterministic.

You're defining an empty vector using it as if has space.

Why are those variables global anyway? If it was local, you wouldn't have these problems as rows/cols would have the required values before grid was declared.
Last edited on
@kbw
I was about to say initializing them to something still gives a segfault.
It can't be any old values, it has be the values the user enters in main().

It's no big deal, a vector can be resized.
Last edited on
Topic archived. No new replies allowed.