这让我在 c++ 中感到困惑 (17( 我想声明一个具有任何大小的二维向量,每个成员本身又是一个 2D 向量。 我想制作已知大小的空向量。事实上,我希望它的大小在声明时设置。 为了获得更好的图片,想象一个经典的数独谜题,其中 9 个房屋在 3x3 网格中,每个房屋在 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 '': 无法从"初始值设定项列表"转换为"标准::矢量>"训练 2 主.cpp
和
错误(活动(E0289 构造函数"std::vector<_Ty、_Alloc>::vector [with _Ty=cell_t, _Alloc=std::分配器]"没有实例与参数列表匹配 训练2 主要.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()
将矢量调整为所需的大小。但是,在声明中做到这一点而不是做额外的过程不是更快吗?因为我想要空向量
通过当前的类型定义,可以轻松使用非方形单元格和板,并且有很多间接寻址来访问元素。如果将其封装在类中,则初始化器可能会丢失当前具有的大部分重复项。
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
声明的向量。
board_t test(3,std::vector<cell_t>(3,std::vector<int>(3)))
// @a^^^^^^^ @b^^^^^^^^^^^^^^^
@a我们有一个cell_t
向量,但@b我们描述一个"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))));