gpt4 book ai didi

c++ - C++ 中高效的 Sum 和 Assignment 运算符重载

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

你好,我正在用 C++ 实现一个矩阵类
我知道有很棒的库可以像 opencv 那样做,但我需要自己做。

例如,如果我实现总和,我可以这样做

class Mat{
public:
double* data;
int rows,cols;

Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}
};

void Sum(Mat& A,Mat& B,Mat& C){
for (int i = 0; i < A.rows*A.cols; ++i){
C.data[i] = A.data[i]+B.data[i];
}
}

int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);

//do the sum
sum(A,B,C);
}

我想得到像这样更具可读性但又不失效率的东西

C = A + B

这样 C 每次都被重新分配,我不想要那样

谢谢你的时间

最佳答案

延迟计算。

class MatAccess {
friend class Mat;
friend class MatOpAdd;
virtual double operator[](int index) const = 0;
};

class MatOpAdd: public MatAccess {
friend class Mat;
private:
const MatAccess& left;
const MatAccess& right;
MatOpAdd(const MatAccess& left, const MatAccess& right):
left(left), right(right) {}
double operator[](int index) const {
return left[index] + right[index];
}
};

class Mat: public MatAccess{
public:
double* data;
int rows,cols;

Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}

MatOpAdd operator +(const MatAccess& other) {
return MatOpAdd(*this, other);
}

const Mat& operator = (const MatAccess& other) {
for(int i = 0; i < rows*cols; ++i) {
data[i] = other[i];
}
return *this;
}
private:
double operator[](int index) const {
return data[index];
}
double& operator[](int index) {
return data[index];
}
};


int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);

//do the sum
C = A + B;
}

现在 '+' 计算将在 "operator="中完成

我会改变的事情:

  • MatAccess 应包含维度(行、列)。
  • Mat 添加构造函数和 operator= 或使其不可复制
  • Mat::operator+Mat::operator= 检查相等的 rows,col
  • 删除不再使用的内存或
  • 使用 std::vector 进行更简单的内存管理。

在这里创建了一个更大的例子:https://gist.github.com/KoKuToru/1d23af4bbf0b2bc89893

关于c++ - C++ 中高效的 Sum 和 Assignment 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27741100/

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