从 C++ 中的 3D 矩阵中提取 2D 矩阵



我正在尝试编写一个函数,该函数给定一个索引作为输入参数,从 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。它甚至不是第一层,但实际上只是垃圾。

newdelete应该出现的唯一时间是在名为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
}

最新更新