[英]Passing 3x3 array by reference C++ error: cannot convert ‘double*’ to ‘double’ in initialization
I am trying to pass a 3x3 array by reference in C++. 我试图通过C ++中的引用传递3x3数组。 However when I do it I get the error error: cannot convert 'double*' to 'double' in initialization.
但是,当我这样做时,我会收到错误错误:无法在初始化时将'double *'转换为'double'。 I tried to follow the instructions given on this page .
我试图按照此页面上的说明进行操作。 I have a for loop in there but I am not going to be using that until I can get the array to pass properly:
我在那里有一个for循环,但是直到可以正确传递数组之前,我不会使用它:
void transpose(double (&arr)[3][3] )
{
for (int counti = 0; counti < 3; counti++) {
for (int countj = 0; countj < 3; countj++) {
double i_swap = &arr[0][0];
}
}
}
int main()
{
double myarray[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
transpose(myarray);
return 0;
}
&
is a reference. &
是参考。 You're trying to set a pointer to a double which you can't like that. 您正在尝试将指针设置为您不喜欢的double。
void transpose(double (&arr)[3][3] )
{
for (int counti = 0; counti < 3; counti++) {
for (int countj = 0; countj < 3; countj++) {
double i_swap = arr[0][0];
}
}
}
int main()
{
double myarray[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
transpose(myarray);
return 0;
}
seems fine, just the swapping part needed (you can ofc use std::swap
from <algorithm>
) 似乎很好,只需要交换部分即可(您可以使用
<algorithm>
std::swap
)
void swap(double& a, double& b)
{
double temp = a;
a = b;
b = temp;
}
Pay attention to the for
-bounds. 要注意
for
-bounds。 final code: 最终代码:
for (int y=1; y<3; y++)
for(int x=0; x<y; x++) {
std::swap(mat[y][x], mat[x][y]); // stl
//swap(mat[y][x], mat[x][y]); // calling your swap function
//double temp = mat[y][x]; // no swap function
//mat[y][x] = mat[x][y];
//mat[x][y] = temp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.