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::gr开发者_Go百科id() : 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 ?
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)) {}
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
@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.
精彩评论