-1

I want to return the matrix from the function, but I can't find a way how. I've found some ways, but they can't be used for VLA. I've read about using std::vector, but that also didn't work.

int gengrid(int gridsize)
{
    gridsize = 10 - 1;
    int grid[gridsize+3][gridsize+3];
    srand(time(NULL));

    int count = 0;

    std::fill_n(grid[0], 12, 0);
    for(int i = 1; i < gridsize + 2; i++)
    {
        grid[i][0] = 0;
        for(int j = 1; j < gridsize + 2; j++)
        {
            grid[i][j] = rand()%2;
        }
        grid[i][gridsize+2] = 0;
    }
    std::fill_n(grid[gridsize+2], gridsize + 3, 0);

    return grid;
}
Wilson CZ
  • 1
  • 1
  • Right now you're returning a local array, which isn't going to work (not to mention the fact it's a VLA). What about `std::vector` didn't work? – Stephen Newell May 14 '21 at 16:03
  • 1
    Does this answer your question? [Return a 2d array from a function](https://stackoverflow.com/questions/8617683/return-a-2d-array-from-a-function) – Abanoub Asaad May 14 '21 at 16:10
  • I've tried to convert it to vector, but then I had a problem with `std::fill_n`. It throws me this error: https://pastebin.com/XnmLqkpi – Wilson CZ May 14 '21 at 16:14
  • You don't really need to use `fill_n` with vectors if you use the constructors that initialize them with a specified number of the specified value, which in this case can be `0`. – Nathan Pierson May 14 '21 at 16:17
  • I'm now wondering, how to initialize vector matrix with zeros. I tried `static std::vector> grid(10, 0)`, but that doesn't work. – Wilson CZ May 14 '21 at 16:36

1 Answers1

0

Okay, I found out my solution.

I initialize vector matrix with

static std::vector<std::vector<int>> grid(gridsize+3, std::vector<int>(gridsize+3));

which sets 0 by default for all elements. (honestly, I don't know, how it's working, maybe somebody would comment explanation of this behavior.)

Complete code here:

#include <iostream>
#include <time.h>
#include <vector>

std::vector<std::vector<int>> gengrid(int gridsize)
{
    gridsize = 10 - 1;
    static std::vector<std::vector<int>> grid(gridsize+3, std::vector<int>(gridsize+3));//[gridsize+3][gridsize+3];
    srand(time(NULL));

    int count = 0;

    for(int i = 1; i < gridsize + 2; i++)
    {
        grid[i][0] = 0;
        for(int j = 1; j < gridsize + 2; j++)
        {
            grid[i][j] = rand()%2;
        }
        grid[i][gridsize+2] = 0;
    }

    return grid;
}

int main()
{
    std::vector<std::vector<int>> grid = gengrid(10);

    for(int i = 0; i < 9 + 3; i++)
    {
        for(int j = 0; j < 9 + 3; j++)
        {
            std::cout << grid[i][j];
        }
        std::cout << std::endl;
    }

    return 0;
}
Wilson CZ
  • 1
  • 1