【问题标题】:C++ : How do I only look at one dimension of a 2-Dimensional array?C++:如何只查看二维数组的一维?
【发布时间】:2018-03-18 10:23:27
【问题描述】:

我正在控制台中编写战舰游戏,并且正在编写一个函数,该函数将基于二维数组绘制一个网格。我采取的方法是这样的:

--> Draw 1 row which contains a character X amount of times (like 10)

--> Draw that row, putting a newline at the end of the drawing process, 10 times to get a nice field.

现在,我确实需要在 1 行的末尾插入一个换行符,对吗?但是如何只比较数组的 x 元素而不比较 y 元素呢?

这是我的代码:

// Includes
#include <iostream> // For IO
#include <cstdlib> // For rand()

// Important game stuff
const int empty = 0; // Water
const int occupied = 1; // Ship
const int hit = 2; // Hit a ship
const int missed = 3; // Missed

// Variables
const int fields = 10;
// We want a 10x10 field
int board[fields][fields]; // board[x][y]

// Initialize board
void initb(int array[fields][fields]);
// Draw board x-axis
void drawbx(int array[fields][fields]);

int main(void)
{
    drawbx(board;)
    // game(Players);
    return 0;
}
// Initialize the board, make everything hit
void initb(int array[fields][fields])
{
    for(int x = 1; x <= 10; x++)
    {
        for(int y = 1; y <= 10; y++)
        {
            array[x][y] = hit;
        }
    }
}

void drawbx(int array[fields][fields])
{
    for(int i = 1; i <= fields; i++)
    {
        if(array[i][] == empty || array[i][] == occupied)
        {
                if(i == 10)
                    std::cout << "  X\n";
                else if(i == 1)
                    std::cout << "X  ";
                else
                    std::cout << "  X  ";
        }
    }
}

具体看一下drawbx()函数。我想画类似的东西

X X X X X X X X X X\n

我尝试的语法if(array[i][] == empty || array[i][] == occupied) 不起作用。第二对方括号中必须有表达式。有人可以帮我吗?

【问题讨论】:

  • 你不能。像array[i][] 这样的代码是非法的。您必须为两者提供索引。喜欢array[i][0]array[i][1]。除此之外,请记住索引从 0 开始到 9。
  • 我不清楚为什么drawbx 只能画一条线。但如果这就是你想要的,你应该这样做:void drawbx(int array[fields][fields], int row_to_draw),然后使用array[row_to_draw][i]。顺便说一句:考虑使用向量而不是数组
  • @4386427 非常感谢。我认为这将解决我的问题。只要回答它,我就可以将其标记为答案。
  • @4386427 我不想尝试一次绘制所有内容,因为这会使我的代码非常不可读。我宁愿控制一行的单个元素,然后打印该行 X 次。

标签: c++ arrays g++ draw


【解决方案1】:

我看到两个主要问题:

1) 数组索引超出范围。您使用索引 1 到 10。它应该是 0 到 9。

2) 代码array[i][] == empty 是非法语法。您不能将一个索引留空。

如果您想要一个绘制一行的函数,可以将行号传递给函数,例如:

void draw_one_row(int array[fields][fields], int row_to_draw)
{
    for(int i = 0; i < fields; i++)
    {
        if(array[row_to_draw][i] == empty || array[row_to_draw][i] == occupied)
        {
            ...
        }
    }
}

绘制整个棋盘:

void draw_board(int array[fields][fields])
{
    for(int i = 0; i < fields; i++)
    {
        draw_one_row(array, i);
    }
}

顺便说一句:由于您编写的是 C++,因此我建议您使用 vector 而不是数组。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 2013-11-23
    • 2012-04-30
    • 2011-03-27
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多