tags:

views:

65

answers:

3

I have a class called Grid 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 is initializing it to be a 9x9 grid. How can I make it work so that the user is asked for a number, say n, and the grid is initialized n x n ?

+5  A: 

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

grid::grid(size_t w, size_t h) : sudoku_(w, row(h)) {}
Georg Fritzsche
but this will initialize it to be 9x9 again...i want it to be n x n where n is entered by user
xbonez
@xbonez: Then let the constructor take parameters - see the update.
Georg Fritzsche
ah, ok....thanks. i'll try this
xbonez
@Downvoter: Care to explain?
Georg Fritzsche
A: 

if you can, do not use vector. Use this instead http://www.boost.org/doc/libs/1_42_0/libs/multi_array/doc/user.html

aaa
thanks but unfortunately we are required to use vectors. its for a homework.
xbonez
+1  A: 

@gf has the absolute right answer for the question, but I'd question the use of vector here (rare for me). In the case of a sudoku grid the structure is fixed size, so you don't win by having easy dynamic allocation. By using a vector of 9 vectors, you have ten populated vector objects. Each one of these has at least one dynamic allocation, so ten calls to new. On top of that, on the implementation of std::vector I am most familiar with the object is 12 bytes (3 32-bit pointers), plus the heap allocation overhead. All of that to deal with a structure which can comfortably be represented in less than 100 bytes is overkill.

Stewart