从 C++ 中的 3D 矩阵中提取 2D 矩阵
Extracting a 2D matrix from a 3D matrix in c++
我正在尝试编写一个函数,该函数给定一个索引作为输入参数,从 3D 矩阵中提取相应的层,返回一个 2D 矩阵。
我的默认 3D 矩阵构造函数如下所示:
Matrice3D(unsigned int depth, unsigned int height, unsigned int width, const T &value) : _3D_matrix(0), _height(0), _width(0), _depth(0) {
try {
_3D_matrix = new T[height * width * depth];
for (int z = 0; z < depth; z++) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
_3D_matrix[y * width * depth + x * depth + z] = value;
}
}
}
}
catch(...) {
delete[] _3D_matrix;
throw;
}
_height = height;
_width = width;
_depth = depth;
}
(try/catch
仍然是一个WIP,我知道这不是一件事情(。
到目前为止,我已经编写了以下内容:
void slice(int index) {
try{
_2D_matrix = new T[_height * _width];
}catch(...){
delete[] _2D_matrix;
_height = 0;
_width = 0;
_depth = 0;
throw;
}
_depth = 1;
for (int k = 0; k< _depth; k++) {
for (int j = 0; j< _height; j++) {
for (int i = 0; i< _width; i++) {
_2D_matrix[j * _width + i] =
_3D_matrix[j * _width * _depth + i * _depth + index];
}
}
}
}
我想使用嵌套for
周期完成的赋值背后的逻辑是正确的,但我真的不知道如何返回新矩阵。 从main
,用于测试代码,我正在调用
std::cout << "--------TEST SLICE------------" << std::endl;
Matrice3D<int> m1(3,3,3,17);
std::cout << "Setter su (0,0,2,99)" << std::endl;
m1(0,0,2,91); //setting a value
m1.slice(2);
std::cout << "Matrix obtained from slicing the layer 2: " <<std::endl;
std::cout << m1;
但是我一直得到矩阵的第一层,无论我为输入选择什么索引。
创建一个新的类 Matrice2D 并在 slice(( 中返回它。
你在代码中得到完全垃圾的原因是你破坏了 3D 矩阵的_depth。它甚至不是第一层,但实际上只是垃圾。
new
和delete
应该出现的唯一时间是在名为something_ptr
的类中。这里不需要原始指针,您应该从slice
返回2DMatrix
。
template <typename T>
class 2DMatrix;
template <typename T>
class 3DMatrix {
std::vector<T> data;
std::size_t height, width, depth;
public:
3DMatrix(std::size_t height, std::size_t width, std::size_t depth, T value = {})
: data(height * width * depth, value),
height(height),
width(width),
depth(depth)
{}
2DMatrix<T> slice(std::size_t index) {
2DMatrix<T> result(height, width);
for (std::size_t i = index; i < data.size(); i += depth) {
result.data[i / depth] = data[i];
}
return result;
}
// other members
}
template <typename T>
class 2DMatrix {
std::vector<T> data;
std::size_t height, width;
friend class 3DMatrix<T>;
public:
2DMatrix(std::size_t height, std::size_t width, T value = {})
: data(height * width, value),
height(height),
width(width)
{}
// other members
}
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 如何使用用户输入在C++中正确填充2D数组
- 为什么istream不支持右值提取
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何设置一个范围来提取我想要获得的信息
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从 C++ 中的 3D 矩阵中提取 2D 矩阵
- 如何在 c++ 中提取 2D 数组的列?
- 从 2d 坐标的列表(矢量)中提取上限和下边界
- 从字符串流中提取到 2D 矢量
- 从 2D 数组C++中提取行或列
- 如何从2D向量中提取单行并分配给1D向量
- 从2d字符串数组中提取字符