c++ - 如何通过重载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],每次用的时候,我都会写一个很长的段...
解决方案
这是你要找的吗?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";
}
推荐阅读
- c++ - 如何获取变量类型并将其存储在模板函数/类中
- r - R函数识别不匹配的行
- django - 哪个 django 字段应该用于计时器?实际的
- javascript - 如何处理事件监听器和共享状态中的竞争条件?
- java - Recyclerview项目的Android循环显示动画不起作用
- awk - 为什么awk在做算术时把一个数字变成字符串?
- html - Bootstrap 导航栏两个或多个项目对齐
- c++ - 如何将 std::wstring 转换为 utf-8 std::string?
- scrapy - Scrapy - 如何发送请求表单
- java - 如何解决数组赋值的 java.lang.NullPointerException