【问题标题】:How can I code a two-dimensional array of 50 rows and 50 columns into a function which randomly assigns an asterisk to an element?如何将 50 行和 50 列的二维数组编码为一个随机为元素分配星号的函数?
【发布时间】:2019-09-04 05:58:50
【问题描述】:

我有一个学习 C++ 的 CS 课程的作业。对于这个任务,我必须编写一个可以传递给函数的二维字符数组。该数组必须由 50 行和 50 列组成。所有元素都必须初始化为空格(' ')。

我在这里创建了数组我还编写了一个 for 循环来将数组放置在网格中。现在,我必须将星号随机分配给数组的元素,这些元素仍然是空白的,我不知道该怎么做。

#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <stdlib.h>

using namespace std;

int main()
{
    const int rows = 50; // Variables
    const int col = 50;
    const char SIZE = ' ';
    const int hgt = 48;
    int X = rand() % 50; // *Edited: This code was copied from an older save
    int y = rand() % 50;

    char board[rows][col]; // Array initialization
    int i;
    int j;
    int x;

    srand((unsigned)time(0));  
    for (i = 0; i < rows; i++) // For loop to place array in grid.
    {
        for (j = 0; j < col; j++)
        {
            board[i][j] = SIZE;
        }
            board[x][y] = '*'
   }

    cout << setfill('-') << setw(50) << "" << endl; // Grid
    for (X = 0; X < hgt; X++)
    {
        cout << "|" << setfill(' ') << setw(49) << "|" << endl;
    }
    cout << setfill('-') << setw(50) << "" << endl;

        cin.ignore();
    cout << "Press Enter to continue..." << endl;
    cin.ignore();
    return 0;
}

数组有效,网格有效。我只是不知道如何分配随机放置在网格中的星号以及如何将该数组传递给函数。

【问题讨论】:

  • 为什么board[x][y] = '*'for 里面?它总是做同样的事情,没有必要重复它。另外,在“打印”地图时,为什么不使用数组的值?至于放置星号,您可以使用一个星号。如果您需要更多添加循环。
  • 将初始填充字符称为“SIZE”是很奇怪的。在什么方面你觉得它是一个大小? (单词的含义不会因为涉及计算机而消失。说你的意思;说你想说的。)
  • 您用 c++ 标记了这个问题,但您使用的是 c 编码风格。使用std::arrayrange based for loops、<random><algorithm>
  • 不要使用using namespace std。不要同时包含&lt;cstdlib&gt;include &lt;stdlib.h&gt;。选择一个
  • 好点。您可以(也可以不)推荐您的老师观看此视频Stop Teaching C。 ;-) 我必须承认我首先学习了 C(几十年前),后来又转向了 C++(几十年前),恐怕我还在学习。很难将 C 习惯留在 C++ 中,因为他们中的大多数人仍在使用 C++(不知何故)......

标签: c++ function multidimensional-array


【解决方案1】:

关于

如何将该数组传递给函数

数组是函数参数的一种特殊情况:

void f(int a[10]);

看起来不像是一个带有int[10] 值参数的函数。数组不是按值传递的——它们衰减为指向第一个元素的指针。因此,上述函数声明与

void g(int *a); // the same as g(int a[]);

如果数组是二维数组(数组的数组),这不会改变:

void f(int a[10][3]);

等同于:

void g(int (*a)[3]); // the same as g(int a[][3]);

指针和维度的混合使事情变得有点复杂:*a 周围的括号是绝对必要的,因为

void h(int *a[3]); // the same as void h(int *a[]); or void h(int **a);

会有一个指向指针的指针作为参数什么是完全不同的东西。

但是,有一个非常简单的技巧可以解决所有这些问题:

使用typedef:

typedef char Board[10][3];

或使用using(更现代):

using Board = char[10][3];

现在,事情变得非常简单:

void f(Board &board); // passing array by reference

也可以写成:

void f(char (&board)[10][3]);

但后者可能看起来有点吓人。

顺便说一句。通过引用传递数组可防止数组类型衰减为指针类型,如下面的小示例所示:

#include <iostream>

void f(char a[20])
{
  std::cout << "sizeof a in f(): " << sizeof a << '\n';
  std::cout << "sizeof a == sizeof(char*)? "
    << (sizeof a == sizeof(char*) ? "yes" : "no")
    << '\n';
}

void g(char (&a)[20])
{
  std::cout << "sizeof a in g(): " << sizeof a << '\n';
}

int main()
{
  char a[20];
  std::cout << "sizeof a in main(): " << sizeof a << '\n';
  f(a);
  g(a);
}

输出:

sizeof a in main(): 20
sizeof a in f(): 8
sizeof a == sizeof(char*)? yes
sizeof a in g(): 20

Live Demo on coliru


关于

我只是不知道如何分配随机放置在网格中的星号

我不能说它比molbdilno短:

你需要反复做。


为了演示,我稍微重新设计了 OP 代码:

#include <iomanip>
#include <iostream>

const int Rows = 10; //50;
const int Cols = 10; //50;

// for convenience
//typedef char Board[Rows][Cols];
using Board = char[Rows][Cols];

void fillGrid(Board &board, char c)
{
  for (int y = 0; y < Rows; ++y) {
    for (int x = 0; x < Cols; ++x) board[y][x] = c;
  }
}

void populateGrid(Board &board, int n, char c)
{
  while (n) {
    const int x = rand() % Cols;
    const int y = rand() % Rows;
    if (board[y][x] == c) continue; // accidental duplicate
    board[y][x] = c;
    --n;
  }
}

void printGrid(const Board &board)
{
  std::cout << '+' << std::setfill('-') << std::setw(Cols) << "" << "+\n";
  for (int y = 0; y < Rows; ++y) {
    std::cout << '|';
    for (int x = 0; x < Cols; ++x) std::cout << board[y][x];
    std::cout << "|\n";
  }
  std::cout << '+' << std::setfill('-') << std::setw(Cols) << "" << "+\n";
}

int main()
{
  srand((unsigned)time(0));
  Board board;
  fillGrid(board, ' ');
  std::cout << "Clean grid:\n";
  printGrid(board);
  std::cout << '\n';
  populateGrid(board, 10, '*');
  std::cout << "Initialized grid:\n";
  printGrid(board);
  std::cout << '\n';
}

输出:

Clean grid:
+----------+
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
+----------+

Initialized grid:
+----------+
|          |
|      *   |
|**  * *   |
|     *    |
|          |
|          |
|*         |
|          |
|    *     |
|   * *    |
+----------+

Live Demo on coliru

【讨论】:

    【解决方案2】:

    这可能是对c++代码风格的理解。避免使用 c 样式数组并使用std::array。不要使用std::rand,而是使用&lt;random&gt;。使用 stl 容器和算法。使用基于范围的 for 循环而不是经典的 for 循环。尽可能使用const

    #include <algorithm>
    #include <array>
    #include <iostream>
    #include <random>
    
    using Board = std::array<std::array<char, 50>, 50>;
    
    void randomFill(Board &board, std::size_t count) {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> disX(0, board.size());
        std::uniform_int_distribution<> disY(0, board[0].size());
        while (count > 0) {
            const std::size_t x = disX(gen);
            const std::size_t y = disY(gen);
            if (board[y][x] == '*') continue;
            board[y][x] = '*';
            --count;
        }
    }
    
    int main() {
        Board board;
        for (auto &row : board) {
            std::fill(std::begin(row), std::end(row), ' ');
        }
    
        randomFill(board, 50);
    
        for (const auto &row : board) {
            for (const auto &field : row) {
                std::cout << field << ' ';
            }
            std::cout << '\n';
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2015-05-10
      相关资源
      最近更新 更多