How do i assign negative indexes to TArrays?

Hi!
How do i allocate negative indexes to TArrays. I tried like this but still throws an error:

Hexes.Reserve(GridRadius*2+1);
for (int32 i = -GridRadius;i <= GridRadius;++i)
{
	Hexes[i].Reserve(GridRadius * 2 + 1);
}

Tried also with SetNumZeroed but still index out of range error (cause setNumZeroed starts from 0 while i need -x

Hi LlttleOldXander,

No negatives, that would be accessing the memory before the TArray begins. - If you know the range of values, you can increment the values by the most negative to make that 0…

Arrays are defined to start at 0, and be contiguous going up from there.

You can re-map your indices. If you know that you want to go between -GridRadius and GridRadius, then simply add GridRadius to the index you use in the array. Thus, item 0 in the array, would correspond to the position -GridRadius. This is probably what I’d do in a case similar to yours.

Another option is to use a TMap<Key, Value> where the Key can be whatever you want – any integer is just fine. You won’t have contiguous values – if you put something in at -2 and at 4 and at 33 then there will only be three items in the map, and all the other values won’t be present.

Thank you. Was a bit confused, thought there was a way to assign negative values (i knew how to calculate my coords in a positive only index but kinda wanted to avoid doing it each time i work with the coords in the map). The TMap suggestion would be good also i think, was trying to stay as efficient as possible, and i just read that TMap is faster than std::map.

Also, is there a downside i can’t think of for using TMap<FIntPoint, AHexTile> ?

If you have a static large grid with a known size I would much rather use a one dimensional TArray and arrange the column after column in it (like it’s done for pixels of a texture). With a little bit of math calculating the index of a tile is a lot faster than searching for a special key in a map, also the map is going to take up more memory because you have to store the FIntPoint keys. Using an index to access a multi dimensional coordinate can be unintuitive, so you should minimize the places where you interact with the raw array and expose it via functions like GetTileAtCoordinate instead

Totally this. Hide the storage implementation from any code that has to access it, just have accessor functions that do the dirty.

I’ve worked on several major pieces of software, in and out of gaming, and there was one common rule for all of them – Never use std:: anything. There are many reasons for that, usually that there is a much better open source implementation, or that there is an implementation in the project that is more suited for the specific project. So, if Unreal provides a data type, most definitely use the Unreal implementation before using a std:: implementation.