简体   繁体   English

选择矢量矢量的大小

[英]Selecting size of vector of vectors

I have a class called Grid that declares a vector of vectors like this: 我有一个名为Grid的类,它声明了这样的向量向量:

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. 如您所见,构造函数将其初始化为9x9网格。 How can I make it work so that the user is asked for a number, say n, and the grid is initialized nxn ? 如何让它工作,以便要求用户输入一个数字,比如n,并且网格初始化为nxn?

vector有一个构造函数,允许您使用给定值的副本将其初始化为特定大小:

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 请改用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). @gf对这个问题有绝对正确的答案,但我在这里质疑vector的用法(对我来说很少见)。 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. 通过使用9个向量的向量,您有10个填充的向量对象。 Each one of these has at least one dynamic allocation, so ten calls to new. 其中每个都至少有一个动态分配,所以十个调用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. 最重要的是,关于std :: vector的实现我最熟悉的对象是12个字节(3个32位指针),加上堆分配开销。 All of that to deal with a structure which can comfortably be represented in less than 100 bytes is overkill. 所有这些处理一个可以在不到100个字节内轻松表示的结构都是过度的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM