Map vs Array

Hi,
I want to know what will be better.

If I want to create a grid wich is contains info on every tile what should I use? Map or Array

Map: keys as int points (X.Y)
Array: Indexes for X. Values will be other arrays. For this arrays Indexes will serve as Y and Values as Tile Info. Will be it consider 2DArray?

1 Like

Possibly a map of Struct → Struct

The key struct is an integer pair, and the value struct is what you want to store.

1 Like

If it’s sparse, use a map. If it’s dense, use an array.

Sparse means if not all tiles have info, then probably quicker and uses less memory with a Map.
If you have a grid and every single tile has info, then use a nested array. Unfortunately, UE doesn’t allow nested arrays. You have to create an array of structs that contains another array. That’s how you get around this limitation.

OR use a normal array and calculate the index with x + y * GridSizeX.

int index = x + y * GridSizeX;
TileInfo& info = Grid[index];

I personally prefer this to nested arrays (especially ones with structs). You could also create a small wrapper class to handle the index calculation for you.

USTRUCT(BlueprintType)
struct FMyGrid
{
  GENERATED_BODY()
public:
  void InitGrid(int GridSizeX, int GridSizeY) { m_GridSizeX = GridSizeX; m_GridSizeY = GridSizeY; Grid.SetNum(GridSizeX * GridSizeY);};
  int CalcIndex(int x, int y) const {return x + y * m_GridSize;};
  TileInfo& GetTileInfo(int x, int y) {return Grid[CalcIndex(x,y)];};
private:
  int GridSize;
  TArray<TileInfo> Grid;
};

Is that will be more perfomant or just more cose?

1 Like

Cose?

It will be easier to use :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.