如何声明二维矢量由二维矢量组成?
How to declare a 2D vector consist 2D vectors?
这让我在 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))));
相关文章:
- 将二维矢量传递给类
- 如何声明二维矢量由二维矢量组成?
- 如何在Visual Studio C++中声明一个二维字符串数组?
- 如何使用智能指针在二维上声明数组?
- 如何声明二维模板化类类型向量?
- 如何在头文件中的类中声明二维数组
- 如何在C++中声明动态二维整数数组
- 如何在数组类中声明二维数组
- (C++)初始化和声明二维向量中的元素
- 静态声明的二维数组C++为类的数据成员
- 如何在 C++ 中的类中声明二维动态数组
- 为什么我可以声明一个二维数组与两个维度大小的变量,但不是新的
- 如何声明二维数组的对象和返回它从一个函数
- 在头文件中声明一个动态分配的二维数组而不知道它的维数
- 如何在c++中声明一个第一维未知的二维数组?
- 双指针二维数组声明int** seq=new int* [n];
- 如何在c++中声明一个类中的二维数组
- 如何在动态二维数组中存储数据,在结构体中声明,该结构体也被c++中的另一个结构体使用
- 在 c++ 中声明和初始化(大型)二维对象数组的正确方法是什么?
- 为什么在声明二维数组时需要硬编码宽度