C++ - 自定义矩阵结构

C++ - custom matrix struct

本文关键字:结构 自定义 C++      更新时间:2023-10-16

我需要使用矩阵,我正在使用这种声明,例如对于int数据类型:

std::vector < vector <int>> my2Dvec(rows, vector <int> (cols));

但是现在我想将其用于多种数据类型,所以我声明了这个模板:

template <typename T>
struct matrix
{
int col, row;
std::vector <std::vector <T>> data;
matrix(int c, int r) : col(c), row(r), data(col, std::vector <T> (row))
{
;
}
};

所以我可以将其用作:

matrix <int> m(10, 10);
...
m.data[1][2] = 0;

现在,我如何使用(如果可能):

m[i][j] = someValue;

?如何实现这样的功能?

你只需要实现一个返回对行的引用的[]运算符:

std::vector<T> & operator[](int i) {
return data[i];
}

由于operator []已经在向量上定义,这就足够了。


关于封装的一点。

这可以这样使用,因为当它被声明为结构体时,使用公共实现,这里没有封装。如果matrix隐藏了它的实现(这是正常的C++方式),你应该简单地声明一个实现operator []Row<T>类型。这只不过是鸭子打字,即使它更多地用于Python或Ruby等动态语言,它甚至可以在C++中提供帮助。

下面是一个通过鸭子类型进行封装的示例:

/*
class Matrix represents a matrix
operator[](int i) returns a reference to the ith Row
Row is an internal type that simply defines the operator[](int j) to return
the ith element in a Row (which is a T&)
*/
template <typename T>
class Matrix {
// implementation
int col, row;
typedef std::vector<T> Row;
std::vector<Row> data;
public: // interface
Matrix(int c, int r): row(r), col(c), data(c, std::vector<T>(r)) {}
// allow to use matrix[i][j]
Row & operator[](int i) {
return data[i];
}
};

您需要以一种返回代理对象的方式实现operator[],您可以在该对象上再次使用该对象operator[]来获取结果。

示例代码:

struct matrix
{
struct Proxy
{
std::vector<int>* vec;
Proxy(std::vector<int>* vec_)
: vec(vec_)
{
}
int& operator[](int index)
{
return (*vec)[index];
}
};
matrix(int c, int r) : col(c), row(r), data(c, std::vector<int>(r))
{
}
Proxy operator[](int index)
{
return Proxy(&data[index]);
}
int col, row;
std::vector<std::vector<int>> data;
};

你必须实现数组下标运算符:

int& operator[](std::size_t i) { return data[i]; }