如何声明一个二维向量包含二维向量?

How to declare a 2D vector consist 2D vectors?

这让我在 C++ 中感到困惑 (17) 我想声明一个任意大小的二维向量,每个成员又是一个二维向量本身。 我想制作已知大小的空向量。事实上,我希望在声明时设置它的大小。 为了获得更好的画面,想象一个经典的数独游戏,在 3x3 网格中有 9 个房子,每个房子在 3x3 网格中有 9 个单元格。

    #include<iostream>
    #include <vector>
    using cell_t = std::vector<std::vector<int> >;
    using board_t = std::vector<std::vector<cell_t> >;
    cell_t temp(3, std::vector<int>(3)); //this would be a 2D vector member

现在的问题:

     board_t test(3,std::vector<cell_t>(3,std::vector<int>(3)));//this won't work

编译器错误: 错误 C2440“”:无法从 'initializer list' 转换为 'std::vector>' Training2 main.cpp

错误(活动)E0289 构造函数的实例"std::vector<_Ty, _Alloc>::vector [with _Ty=cell_t, _Alloc=std::allocator]" 不匹配参数列表 Training2 main.cpp 91

不知道我错过了什么?我知道我可以通过临时 cell_t 实现它,例如:

    cell_t temp(3, std::vector<int>(4));
    board_t test(3,std::vector<cell_t>(3,temp));

但我更喜欢使用未知对象。
另一方面,我知道如何使用 resize()push_back() 来支持将向量调整到所需的大小。但是,在声明中实现这一点而不是进行额外的处理不是更快吗?因为我想要空向量

您当前的类型定义使得非方形单元格和面板变得容易,并且您有很多间接访问元素的方法。如果您将其封装在 class 中,您的初始化程序可能会丢失您当前拥有的大部分重复项。

struct index_t {
    std::size_t x;
    std::size_t y;
};

template <typename T>
class square_matrix {
    std::size_t size;
    std::vector<T> elems;

    std::size_t position(index_t index) { return index.x + (index.y * size); }

public:
    square_matrix(std::size_t size, T elem = {}) : size(size), elems(size * size, elem) {}
    T& operator[](index_t index) { return elems[position(index)]; }
    const T& operator[](index_t index) const { return elems[position(index)]; }
};

using cell_t = square_matrix<int>;
using board_t = square_matrix<cell_t>;

board_t test(3, cell_t(3));

原来问题出在定义cell_t声明的vector


     board_t test(3,std::vector<cell_t>(3,std::vector<int>(3)))
    //                        @a^^^^^^^  @b^^^^^^^^^^^^^^^

@a 我们有一个向量 cell_t 但是 @b 我们描述了一个 'vector of int' 那就是问题所在。 我们应该用 cell_t(3,std::vector<int>(3) 而不是 @b 它应该是这样的:

    board_t test(3, std::vector<cell_t>(3, cell_t(3, std::vector<int>(3))));