2

For a project we have an expanding grid which loads random chunks. In this chunk we place random objects. The chuncks are loaded vertical and horizontal. The player starts at 0,0 going up is 0,-1 going left -1,0. I want to see if a chunk is loaded. Because the area is expanding an array is not an option so i lookee at options with vectors. But vectors cant have negative indexes. How can i store a grid (with 2 posible negative) values and a boolean. Should i just cretate a class with 3 variables (2 ints and a boolean) or are there other options, where i can use some kind of multidimensional vector with negative values.?

Community
  • 1
  • 1
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

2 Answers2

2

You could use a map, for example:

typedef std::pair<int, int> coord;
typedef std::map<coord, bool> coord_bool_map;

usage:

coord_bool_map m;
m[coord(-1, -3)] = true;
alain
  • 11,939
  • 2
  • 31
  • 51
  • What about enclosing this solution (which I think is very pretty) in a class so we're able to define an interface for it? (e.g. `chunk::is_loaded()` or some things like that) – Richard-Degenne Dec 21 '15 at 11:38
  • Hmm, I think I would not do that, but that's just personal taste. The thing *is* a map, so why not keep the already provided interface? – alain Dec 21 '15 at 11:47
0

But vectors cant have negative indexes

No, but you can translate the indices with an offset. Say, you have a vector of size 5, which should represent a one dimensional grid of idices from -2...2:

std::vector<T> grid = std::vector<T>(5);
int offset = 2;                // the offset, also index of origin
int start = -offset;           // first index
int end = grid.size() - offset // one past last index

// example use
int index = -1;
T element_at_index = grid[index + offset];

A std::deque might be more efficient for expanding the container from the front side.

When you do expand the front side, remember to update the offset.

If you use a vector of vectors (or deques), then you need an offset for both dimensions.

eerorika
  • 232,697
  • 12
  • 197
  • 326