阵列输出网格上的x和y轴



我正试图将数组输出到2D网格中(但这不是问题所在(,但是x和y轴的范围将是用户输入的任何值(例如,x轴可以是0-8,也可以是0-10,这取决于用户的偏好(。我的意思是,我只能硬编码,使x和y轴的范围是固定的。类似的东西:

char gridArray[5][5];
for( int i = 0; i < 5; i++ )
{
for( int j = 0; j < 5; j++ )
{
gridArray[i][j] = 'O';
}
}
for( int i = 0; i < 5; i++ )
{
out << i + 1 << "  ";
for( int j = 0; j < 5; j++ )
{
out << gridArray[i][j] << "  ";
}
out << endl;
}

如注释中所述,您可能应该将std::vector用于动态数组。例如

#include <iostream>
#include <vector>
#include <cstddef>
int main()
{
std::cout << "Enter x and y size, followed by enter: ";
std::size_t nrOfRows, nrOfCols;
std::cin >> nrOfRows >> nrOfCols;
// initialize dynamic array of arrays
std::vector<std::vector<char>> data(nrOfRows,
std::vector<char>(nrOfCols, 'O'));
// print array
for (std::size_t rowNr = 0; rowNr < nrOfRows; rowNr++)
{
std::cout << "Row " << rowNr << ": ";
for (const auto& el : data[rowNr])
std::cout << el << " ";
std::cout << std::endl;
}
}

如果我没有误解你的话,你需要使用动态内存分配,这样你就可以写这样的代码:

int x, y; //  input these varialbles in any way
char ** array = new char* [y];
for (int i = 0; i < y; i++) {
array[i] = new char[x];
}
// your code setting and showing the array
for (int i = 0 i < y; i++) {
delete [] array[i];
}
delete [] array;

(对不起,我用的是手机,所以格式可能有点不正确(

最新更新