Making this structure using 2D Array

https://imgur.com/a/Ragasr3
How can I make this?
Last edited on
If I understand your question, it's probably best to only store the part that changes in your 3 rows by 6 columns array. The lines can be drawn when you output it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <algorithm>

constexpr int ROWS = 3;
constexpr int COLS = 6;

void draw_board(char board[ROWS][COLS])
{
    using std::cout;
    for (int col = 0; col < COLS; ++col) cout << "+---";
    cout << "+\n";

    for (int row = 0; row < ROWS; ++row)
    {
        cout << "| ";
        for (int col = 0; col < COLS; ++col)
            cout << board[row][col] << " | ";
        cout << '\n';
        for (int col = 0; col < COLS; ++col) cout << "+---";
        cout << "+\n";
    }
}

int main()
{
    char board[ROWS][COLS]; // I'm assuming you want characters
    std::fill(&board[0][0], &board[ROWS][0], ' ');

    // set a couple of arbitrary locations to arbitrary chars
    board[1][2] = 'x';
    board[2][4] = 'y';
    board[0][1] = 'z';

    draw_board(board);
}

+---+---+---+---+---+---+
|   | z |   |   |   |   | 
+---+---+---+---+---+---+
|   |   | x |   |   |   | 
+---+---+---+---+---+---+
|   |   |   |   | y |   | 
+---+---+---+---+---+---+

A more C++y option is to use a std::array of std::array instead of the low-level array.
You could also use better box-drawing characters than I've used (https://en.wikipedia.org/wiki/Box-drawing_character).

EDIT: Here's how it looks with the nicer box-drawing characters.
┌───┬───┬───┬───┬───┬───┐
│   │ z │   │   │   │   │ 
├───┼───┼───┼───┼───┼───┤
│   │   │ x │   │   │   │ 
├───┼───┼───┼───┼───┼───┤
│   │   │   │   │ y │   │ 
└───┴───┴───┴───┴───┴───┘
Last edited on
Topic archived. No new replies allowed.