首页 > 解决方案 > 如何通过重载C++中的函数调用运算符来获得存储在一维数组中的二维数组?

问题描述

我在空闲时间编写一个小型科学计算库。而且我发现有人说将二维数组存储在一维数组中更快,您可以通过重载函数全部运算符来做到这一点。但我不知道如何处理它。

现在我认为函数数组应该这样做:

#include<iostream>
int main(){
    int M=10;
    int N=10;
    double x[M*N];
    cout<<x(m,n)<<endl;//print the m*N+n element of x
    return 0;
}

我该怎么办?或者任何地方都说过。我在stackoverflow中看不到它......

x[m*N+n] 对于二维条件很有用。但是如果我有四个维度,那就是x[m*A+n*B+p*C+l*D],每次用的时候,我都会写一个很长的段...

标签: c++arraysclassoperator-overloadingscientific-computing

解决方案


这是你要找的吗?Matrix1D 类有一个一维向量,但模拟一个二维矩阵,并允许您使用 () 运算符来访问它。

您可以通过修改 operator(...) 和 set(...) 函数将其扩展到任意数量的维度。

#include <iostream>
#include <vector>

class Matrix1D {
 private:
  std::vector<double> x;
  int N;

 public:
  Matrix1D(int m, int n) {
    this->x = std::vector<double>(m * n);
    this->N = n;
  }

  double operator()(int m, int n) { return this->x[m * this->N + n]; }

  void set(int m, int n, double v) { this->x[m * this->N + n] = v; }
};

int main() {
  Matrix1D c1(5, 5);
  c1.set(3, 2, 1);
  std::cout << c1(3, 2) << "\n";
}

推荐阅读