如何通过发送多维数组的引用来输出多维数组

  • 本文关键字:数组 引用 输出 何通过 c++
  • 更新时间 :
  • 英文 :


我需要一些帮助来输出这个多维数组的内容。我正在尝试将数组的地址传递给函数,让它抓取并运行它。

#include <iostream>
using namespace std;
void LoopDeLoop(int[][] *arr)
{
for(int k = 0; k < 3; k++)
{
for(int j = 0; j < 4; j++)
{
cout << arr[k][j];
}
}
}
int main() {
int arr[3][4] = { {1,2,3,4}, {5,6,7,8}, {10,11,12,13} };

LoopDeLoop(&arr);
return 0;
}

您尝试使用的这个模式是老式的C.

现代C++的方法应该对你更清楚:

#include <array>
#include <iostream>
using MyArray = std::array<std::array<int, 4>, 3>;
void LoopDeLoop(const MyArray& arr)
{
for (auto& row : arr) {
for (auto x : row) {
std::cout << x << ' ';
}
std::cout << 'n';
}
}
int main()
{
MyArray arr { std::array { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 10, 11, 12, 13 } };
LoopDeLoop(arr);
return 0;
}

https://godbolt.org/z/Mbcjf9bx5

C++允许通过引用传递普通数组,还可以使用模板自动推导维度:

在线试用!

#include <iostream>
using namespace std;
template <int Rows, int Cols>
void LoopDeLoop(int const (& arr)[Rows][Cols])
{
for(int k = 0; k < Rows; k++)
{
for(int j = 0; j < Cols; j++)
{
cout << arr[k][j];
}
}
}
int main() {
int arr[3][4] = { {1,2,3,4}, {5,6,7,8}, {10,11,12,13} };

LoopDeLoop(arr);
return 0;
}

输出:

1234567810111213

最新更新