0

I'm trying to create a matrix, using 2D vector. I don't understand why compiler gives me error of segmentation fault. Any idea? :)

here is my code:

 #include <iostream>
 #include <vector>
 using namespace std;

 int main(){
 vector < vector <int> > Board;
 int n;
 cout<<"Enter size: ";
 cin>>n;
 Board.resize(n);

   //Initialize with something
 for(int ii=0; ii<n; ii++)
 {
 for (int jj=0; jj<n; jj++)
    Board[i][j]=1;
  }

  //Show vector 
  for(int i=0; i<n; i++)
  {
    for (int j=0; j<n; j++)
   {
    cout<<Board[i][j]<<" ";
   }
    cout<<endl;
   }
  return 0;
 }

I also tried to fill vector with the expression "Board.at(i).at(j)=1" but nothing happen.

zzari
  • 283
  • 1
  • 5
  • 13

2 Answers2

4

After this:

Board.resize(n);

you have a vector containing n empty vectors. You then proceed to access those as if they had n elements. If you want your vector to look like an n by n matrix, you can initialize it like this:

vector <vector<int>> Board(n, std::vector<int>(n));

Note that there is some overhead here. A vector of vectors is more like a dynamic array of pointers to arrays. It might make more sense to use a single vector, provide an two index interface to simulate a 2D array.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Board.resize(n) is only resizing the outer-most vector. If you want a square board, you also need to resize the inner vectors. Try Board.resize(n, std::vector<int>(n)).

Also, while I (may) have your attention, it's generally considered bad practice to say using namespace std; at the top of your file. It's better to fully qualify names in the standard library. For example, std::vector, or, for the very paranoid, ::std::vector.

Community
  • 1
  • 1
anjruu
  • 1,224
  • 10
  • 24