Selecting the size of a vector of vectors

I have a Grid class that declares a vector of vectors like this:

typedef vector<int> row;
typedef vector<row> myMatrix;

myMatrix sudoku_;

      

The constructor looks like this:

grid::grid() : sudoku_(9,9)
{

}

      

As you can see, the constructor initializes it with a 9x9 grid. How can I get it to work so that the user asks for a number, say n, and the nxn grid is initialized?

+2


a source to share


3 answers


vector

has a constructor that allows you to initialize it to a specific size with copies of a given value:



grid::grid(size_t w, size_t h) : sudoku_(w, row(h)) {}

      

+6


a source


if you can, don't use vector. Use this instead of http://www.boost.org/doc/libs/1_42_0/libs/multi_array/doc/user.html



+1


a source


@gf has the absolute correct answer to the question, but I would question the use of a vector here (rare for me). In the case of a sudoku grid, the structure is of a fixed size, so you do not benefit from light dynamic distribution. Using a 9-vector vector, you have ten populated vector features. Each of them has at least one dynamic allocation, so ten calls to the new one. Also, when implementing std :: vector, I'm most familiar with the object: 12 bytes (3 32-bit pointers), plus the overhead of heap allocation. Anything that deals with a structure that can conveniently be represented in less than 100 bytes is overkill.

+1


a source







All Articles