How to code grid perimeters

closed account (9h5X216C)
Hi, I'm new to c++. How can I create a simple grid map using a 2D array, in C++?

Like below illustration as an EXAMPLE:

1
2
3
4
5
6
7
8
9
10

  # # # # # #
5 #  1      #
4 #         #
3 #     1   #
2 #         #
1 #         #
0 # # # # # #
  0 1 2 3 4 5


The '1' is just a random representation of id value.(values taken from a .text file)
Last edited on
Might be easier to use an array of string like so.
1
2
3
4
5
6
7
8
9
10
string grid[] =
{
  "######",
  "# 1  #",
  "#    #",
  "# 1  #",
  "#    #",
  "#    #",
  "######"  
};

other wise
1
2
3
4
5
char [6][6] =
{
  {'#','#','#','#','#','#'},
  // and so on 
};


Another option (probably the best) would be a vector of string so you don't need to know beforehand how many rows and cols the grid has.
Last edited on
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <string>
#include <vector>
#include <random>

using namespace std;

void HeaderFooter(int num_cols)
{
    cout << "  #";
    for (int c=0; c<num_cols+1; ++c)
        cout << " #";
    cout << '\n';
}

// Adds a border and row/col indices around the data
void ShowBoxed(vector<vector<string>>& grid)
{
    int num_cols = grid[0].size();

    // Header line
    HeaderFooter(num_cols);
    
    // Body
    for (int r=0; r<grid.size(); ++r)
    {
        cout << r << " #";
        for (auto& ele : grid[r])
            cout << ' ' << ele;
        cout << " #\n";
    }

    // Footer line
    HeaderFooter(num_cols);

    // Footer label
    cout << "   ";
    for (int c=0; c<num_cols; ++c)
        cout << ' ' << c;
    cout << '\n' << '\n';
}

int main() 
{
    random_device rd;
    const int LOW = 4;
    const int HIGH = 10;

    // Random number of rows and columns, from low to high
    int num_rows = rd()%(HIGH-LOW+1) + LOW;
    int num_cols = rd()%(HIGH-LOW+1) + LOW;
    vector<vector<string>> grid;
    grid.reserve(num_rows);
    vector<string> row;
    row.reserve(num_cols);
    for (int x=0; x<num_cols; ++x)
        row.push_back(" ");

    for (int x=0; x<num_rows; ++x)
        grid.push_back(row);

    cout << "Grid with " << num_rows << " rows and " << num_cols << " columns\n\n";
    grid[1][2] = "x";
    grid[2][0] = "y";
    cout << "(1,2) = x\n";
    cout << "(2,0) = y\n\n";

    ShowBoxed(grid);

    return 0;
}


Possible output
Grid with 8 rows and 10 columns

(1,2) = x
(2,0) = y

  # # # # # # # # # # # #
0 #                     #
1 #     x               #
2 # y                   #
3 #                     #
4 #                     #
5 #                     #
6 #                     #
7 #                     #
  # # # # # # # # # # # #
    0 1 2 3 4 5 6 7 8 9
Topic archived. No new replies allowed.