'Creating a matrix with unique pointers and 'empty'cells

I'm quite new to coding and am running into a problem. I'm working with matrices and previously I had only integers inside them representing the state of a cell. I initiliazed my grid in the following way:

    const int N = 50; // Grid size
    // 3 vectors for 3 different antibiotics 
    std::vector<std::vector<int> > gridAB1(N, std::vector<int>(N));

    std::vector<std::vector<int> > gridAB2(N, std::vector<int>(N));

    std::vector<std::vector<int> > gridAB3(N, std::vector<int>(N)); 

After which I would change the 0's in these grids at random positions to a certain value. Now I'm moving into a more complex setting where cell state can't be defined as easily as just an integer. I will create a class or struct to represent the cells. I was now recommended to have a grid with at positions (unique) pointers pointing to this struct or class. However I'm very unsure of how to initialize this and how to define between empty places in the grid and places with a cell cause only at a few places in the grid should there actually be a pointer pointing to the struct or class, the rest of the grid would just be "empty". If anyone has any tips or ways of achieving something like this that would be great.

c++


Solution 1:[1]

If your data is a class/struct named Cell then the analog to your first example would be

#include <memory>
#include <vector>

std::vector<std::vector<std::unique_ptr<Cell>>> grid(N, std::vector<std::unique_ptr<Cell>>(N));

In this case you can "initialize" a Cell by constructing it such as

grid[i][j] = std::make_unique<Cell>(args);

or modify a cell similarly

grid[i][j]->some_method();

Though if your Cell is "simple" (small, POD, trivially copyable and moveable, etc) I would just store by value

std::vector<std::vector<Cell>> grid(N, std::vector<Cell>(N));

Then you'd need some way to determine if the Cell was "filled" yet, like keeping a bool member on the Cell like initialized or something. But the matrix access would look the same

grid[i][j] = Cell(args);

grid[i][j].some_method();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cory Kramer