MetalMagnum MetalMagnum - 2 months ago 24
C++ Question

C++ Instantiate 2D Vector inside Struct with default values

Using C++11, I initially had a 2d vector of the following form with default values:

vector<vector<int>> upper({{1,2,3,4,5,6},{7,8,9,10,11,-1},{12,13,14,15,-1,-1},{16,17,18,-1,-1,-1},{19,20,-1,-1,-1,-1},{21,-1,-1,-1,-1,-1}});
vector<vector<int>> lower({{0,0,0,0,0,0},{0,0,0,0,0,-1},{0,0,0,0,-1,-1},{0,0,0,-1,-1,-1},{0,0,-1,-1,-1,-1},{0,-1,-1,-1,-1,-1}});


This represented the upper and lower component of a puzzle I'm trying to solve. Now I want to modify my program such that these vectors are declared inside a struct, but I'm not sure how to do this and give the 2d vectors default values. This is what I have at the moment:

struct BoardState{
vector<int> row;
vector<vector<int>> upper;
vector<vector<int>> lower;

BoardState() : row(6,0), upper(6,row), lower(6,row) {};
};


But it causes a seg fault when I try to access what's inside, using:

#include <iostream>
#include <vector>
#include <stdlib.h>

BoardState *board;
int main(){
using namespace std;
...
for(int i=0; i<6; i++){
for(int j=0; j<6; j++){
cout << board->upper[i][j] << " ";
}
cout << endl;
}

}


How do I give default values to a 2d vector inside a struct? Thanks.

Answer

I'm not sure how to do this and give the 2d vectors default values.

Exactly as outside the struct

#include <vector>
#include <iostream>

struct BoardState
 {
   std::vector<std::vector<int>> upper{{1,2,3,4,5,6},{7,8,9,10,11,-1},
                                       {12,13,14,15,-1,-1},{16,17,18,-1,-1,-1},
                                       {19,20,-1,-1,-1,-1},{21,-1,-1,-1,-1,-1}};
   std::vector<std::vector<int>> lower{{0,0,0,0,0,0},{0,0,0,0,0,-1},
                                       {0,0,0,0,-1,-1},{0,0,0,-1,-1,-1},
                                       {0,0,-1,-1,-1,-1},{0,-1,-1,-1,-1,-1}};
   std::vector<int> row;

   BoardState()
    { }
 };

int main()
 {
   BoardState bs;

   std::cout << bs.upper[3][1] << std::endl;   // print 17
 }

or

struct BoardState
 {
   std::vector<int> row {6, 0};
   std::vector<std::vector<int>> upper {6, row};
   std::vector<std::vector<int>> lower {6, row};

   BoardState()
    { }
 };

(in this case, print 0).

Thake in count that, as explained by ArchbishopOfBanterbury and Petter, member are initialized in the order they are declared; so, if you want to initialize upper and lower using row, you have to declare row before.

Comments