我在创建 PRINT 函数时遇到问题,我将能够使用不同的数组大小运行多次。我将以此为例。
飞机座位表:
2 sections
-First Class
--5 rows
--2 columns
---2 seats/column
-Coach Class
--5 rows
--2 columns
---3 seats/column
视觉: Example - Plane seating chart
问题 1:如何打印出来?
问题 2:如何创建一个函数来多次传递 this?
有问题的代码(从二维角度来看)
#include <iostream>
#include <iomanip>
using namespace std;
const int COLS = 4;
const int ROW1 = 3, ROW2 = 4;
void showArray(const int [][COLS],int);
int main()
{
int table1 [ROW1][COLS] = {{1,2,3,},{6,7,8,9}};
int table2 [ROW2][COLS] = {{9,8,7,6},{5,4,3,2}};
cout << "Table 1 Array: \n" << endl;
showArray(table1,ROW1);
cout << "Table 2 Array: \n" << endl;
showArray(table2,ROW2);
return 0;
}
void showArray (const int array[][COLS], int rows)
{
for(int x = 0; x < rows; x++)
{
for (int y = 0; y < COLS; y++)
{
cout << setw(4) << array[x][y] << " ";
}
cout << endl;
}
}
上面的代码是一个示例,说明如果需要确定行数,我需要做什么……正确吗?
现在我知道代码没有给我正确的打印输出,因为它把 0 放在空白处,我知道当没有列出 x 的第 4 个值时,这对 y(或 COLS)循环 4 次
关于如何创建一个可以多次使用不同数组大小且不给我 0 的函数的任何想法?
在这种特殊情况下,我可以将 CONST INT 分配给“行”,因为它们本质上是 2 个 5 的数组,但如果我将每个座位都算作新列,它们将具有不同的 Y(列)值。
除非有一种方法可以保持相同的列数 (2) 并在每列中显示多个座位,无论是头等舱还是经济舱。
任何想法都会很棒。感谢你们的帮助!
最佳答案
如果这不是您要的,请告诉我。下面是一个关于如何打印任意大小的多维数组的示例。对于这个例子,我使用了 std::vector
作为容器。请注意,这是 C++11,它不会用 C++98 编译(如果你想用 C++98 编译器编译这段代码,你需要使用迭代器而不是基于范围的 for 循环)
#include <iostream>
#include <vector>
void show(const std::vector<std::vector<int>>& matrix)
{
for(auto& vector : matrix) {
for(auto& element : vector) {
std::cout << element << " ";
}
std::cout << std::endl;
}
}
int main()
{
std::vector<std::vector<int>> matrix1;
matrix1.push_back({1,2,3});
matrix1.push_back({4,5,6});
matrix1.push_back({7,8,9});
std::vector<std::vector<int>> matrix2;
matrix2.push_back({1,2,3,4,5});
matrix2.push_back({6,7,8,9,10});
std::cout << "Matrix1: " << std::endl;
show(matrix1);
std::cout << "Matrix2: " << std::endl;
show(matrix2);
}
关于c++ - 当存在 2 个不同大小时打印函数多维数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23719714/