如何将动态矩阵调用到函数中
How to call a dynamic matrix into a function?
我以这种方式声明了一个矩阵:
double **MB;
MB = new double *[650000];
for (int count = 0; count < 650000; count++)
MB[count] = new double [2];
现在我想在一个应该修改它的函数中调用我的矩阵。
bool notindic (..., double MB [][2], ...) {}
主要:
notindic(..., MB, ...)
现在它给了我这个错误:*[错误] 无法将参数"3"的"双**"转换为"双 ()[2]" 到"bool notindic(std::string, std::string, double ()[2], int, int)'
我该如何解决它?
谢谢。
只需将数组指针作为参数传递即可
#include <iostream>
const int NX = 65;
const int NY = 2;
bool notindic(double** MB) {
for(int i = 0; i < NX; ++i) {
for(int j = 0; j < NY; ++j) {
MB[i][j] = i + j;
}
}
}
int main() {
double **MB = new double *[650000];
for (int count = 0; count < 650000; count++) {
MB[count] = new double [2];
}
notindic(MB);
for(int i = 0; i < NX; ++i) {
for(int j = 0; j < NY; ++j) {
std::cout << MB[i][j] << " ";
}
std::cout << std::endl;
}
}
忘记所有指针废话。它容易出错,异常不安全,难以编写,难以阅读,难以维护,并且可能性能不佳。将矩阵表示为std::vector<double>
并相应地计算偏移量。
bool notindic (std::vector<double> const& matrix, int m) {
// ...
auto const element = matrix[y * m + x];
// ...
}
auto const m = 650000;
auto const n = 2;
std::vector<double> my_matrix(m * n);
auto const result = notindic(my_matrix, m);
当你在它的时候,把它包装在这样的类中:
template <class T>
class Matrix final
{
public:
Matrix(int m, int n) :
data(m * n),
m(m)
{
}
T& operator()(int x, int y)
{
return data[y * m + x];
}
T const& operator()(int x, int y) const
{
return data[y * m + x];
}
private:
std::vector<T> data;
int m;
};
bool notindic (Matrix<double> const& matrix) {
// ...
auto const element = matrix(x, y);
// ...
}
auto const m = 650000;
auto const n = 2;
Matrix<double> my_matrix(m, n);
auto const result = notindic(my_matrix);
如果需要,请添加其他成员函数。
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?