C++ - 自定义矩阵结构
C++ - custom matrix struct
我需要使用矩阵,我正在使用这种声明,例如对于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]; }
相关文章:
- 通过 NIF 从C++返回自定义数据结构
- C++ 通过函数传递自定义结构
- 在C++中循环访问自定义结构列表的小问题
- 自定义数据结构的优点是什么?
- 如何在Qt中使用QDataStream将自定义结构保存/加载到二进制文件中?
- 为什么在类或结构中传递自定义比较器函数?
- 如何在自定义 LLVM 传递之间正确传递数据结构
- 结构向量中自定义结构函数的内存使用
- 类型转换自定义结构
- 使用结构绑定更改自定义结构的值
- 信号槽自定义结构问题
- 如何将unordered_set与自定义结构一起使用?
- 为什么C++在自定义结构向量时会出现 ostream 重载问题?
- 通过自定义结构和链接列表类中的C 中的哈希表
- 从自定义结构数组中提取数据
- 将 OpenGL VBO 与自定义类/数据结构一起使用
- 无法使用自定义结构的属性
- 通过引用将自定义结构的向量传递给 boost::compute 闭包或函数
- 自定义链表创建 RtlValidateHeap 错误,其结构具有链表
- 如何为C++类和结构自定义 STAssertEquals 输出