gpt4 book ai didi

c++ - 用C++实现自然动态矩阵

转载 作者:行者123 更新时间:2023-11-30 02:04:14 24 4
gpt4 key购买 nike

我实际上对同一个想法有 2 个问题:

我想创建一个 TruthMatrix 类,我该如何:

  1. 分配一个动态的 nXn bool 矩阵,唯一的方法是如下吗?:

class TruthMatrix {

        bool **mat;
public:
TruthMatrix(int n) {
mat=new bool*[n];
for (int i=0;i<n;i++) {
mat[i]=new bool[n];
}
}
};
  1. 覆盖 [][] 运算符以快速访问 mat[i][j] 中的矩阵元素

谢谢!

最佳答案

  1. 不,这不是唯一的方法。您可以用一个大数组模拟一个矩阵,并且可以使用 STL 容器来简化内存管理(对于一个)。 (或者使用 dynamic_bitset 或类似的)。

  2. 这可能不值得。矩阵类通常以 operator() 为下标,因为它更容易实现。要使用几个方括号(类似于数组的数组)来完成它,您需要一个合适的代理对象从您的 operator[] 返回(请注意,没有 operator[][ ]).

例子:

class TruthMatrix {
/* ... */
bool& operator()(int row, int column); // usage: matrixobj(1, 2)
};
// or
class TruthMatrix {
/* ... */
class Proxy {
/* ... */
bool& operator[](int column);
};
Proxy operator[](int row); // usage: matrixobj[1][2]
};

关于c++ - 用C++实现自然动态矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com