这使我在C++(17)中感到困惑,我想声明一个任意大小的二维向量,它的每个成员本身也是一个二维向量。 我想做已知大小的空向量。 实际上,我希望它的大小设置为声明。 为了更好的图片,想象一个经典的sodoku拼图,有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“:无法从”initializer list“转换为”std::vector>;“ 培训2 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<board_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));