我有一个函数,我想把它作为一个参数,一个可变大小的二维数组。
到目前为止,我有这个:
void myFunction(double** myArray){
myArray[x][y] = 5;
etc...
}
我在代码的其他地方声明了一个数组:
double anArray[10][10];
然而,调用myFunction(anArray)会给我一个错误。
我不想在传入数组时复制它。在myFunction中所做的任何更改都应该改变anArray的状态。如果我理解正确,我只想传递一个指向2D数组的指针作为参数。该函数还需要接受不同大小的数组。比如[10][10][5][5]。我该怎么做呢?
对shengy第一个建议的修改,你可以使用模板让函数接受多维数组变量(而不是存储一个必须被管理和删除的指针数组):
template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
printf("%p\n", &arr);
}
int main()
{
double a1[10][10];
double a2[5][5];
printf("%p\n%p\n\n", &a1, &a2);
func(a1);
func(a2);
return 0;
}
打印语句用于显示数组是通过引用传递的(通过显示变量的地址)
你可以使用c++中的模板功能来实现这一点。我是这样做的:
template<typename T, size_t col>
T process(T a[][col], size_t row) {
...
}
这种方法的问题在于,对于您提供的每一个col值,都会使用模板实例化一个新的函数定义。
所以,
int some_mat[3][3], another_mat[4,5];
process(some_mat, 3);
process(another_mat, 4);
实例化模板两次以生成2个函数定义(其中一个col = 3,另一个col = 5)。
这是一个向量中的向量矩阵的例子
#include <iostream>
#include <vector>
using namespace std;
typedef vector< vector<int> > Matrix;
void print(Matrix& m)
{
int M=m.size();
int N=m[0].size();
for(int i=0; i<M; i++) {
for(int j=0; j<N; j++)
cout << m[i][j] << " ";
cout << endl;
}
cout << endl;
}
int main()
{
Matrix m = { {1,2,3,4},
{5,6,7,8},
{9,1,2,3} };
print(m);
//To initialize a 3 x 4 matrix with 0:
Matrix n( 3,vector<int>(4,0));
print(n);
return 0;
}
输出:
1 2 3 4
5 6 7 8
9 1 2 3
0 0 0 0
0 0 0 0
0 0 0 0
我们可以使用几种方法将2D数组传递给函数:
Using single pointer we have to typecast the 2D array.
#include<bits/stdc++.h>
using namespace std;
void func(int *arr, int m, int n)
{
for (int i=0; i<m; i++)
{
for (int j=0; j<n; j++)
{
cout<<*((arr+i*n) + j)<<" ";
}
cout<<endl;
}
}
int main()
{
int m = 3, n = 3;
int arr[m][n] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
func((int *)arr, m, n);
return 0;
}
Using double pointer In this way, we also typecast the 2d array
#include<bits/stdc++.h>
using namespace std;
void func(int **arr, int row, int col)
{
for (int i=0; i<row; i++)
{
for(int j=0 ; j<col; j++)
{
cout<<arr[i][j]<<" ";
}
printf("\n");
}
}
int main()
{
int row, colum;
cin>>row>>colum;
int** arr = new int*[row];
for(int i=0; i<row; i++)
{
arr[i] = new int[colum];
}
for(int i=0; i<row; i++)
{
for(int j=0; j<colum; j++)
{
cin>>arr[i][j];
}
}
func(arr, row, colum);
return 0;
}
如果你想将int的[2][3]传递给void func(int** pp),你需要以下辅助步骤。
int a[2][3];
int* p[2] = {a[0],a[1]};
int** pp = p;
func(pp);
由于第一个[2]可以隐式指定,因此可以进一步简化为。
int a[][3];
int* p[] = {a[0],a[1]};
int** pp = p;
func(pp);