Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

Multidimensional array in C++?

Today, I have a general question about storing objects/structs or some other values in a multidimensional array.

The actual scenario is as follows, but I might need similar solutions in many other places, which is why I want to ask you about the best-practice to this.

Suppose we have a side scrolling game. Now I need to store information about the cells of the world in some kind of 2-dimensional array, where 0:0 would be the home-position. At the beginning of the game, I generate a small area of the world, say from -10:-5 to 10:5. The player could move left or right (and sometimes up and down), so I have to generate more world information when he reaches the edges of the world. Now my question: How am I supposed to store a 2-dimensional array with varying extremes? Are there any best practices around how to do this? What would you do?

Thanks again for all your help!

Upvotes: 0

Views: 110

Answers (2)

SigTerm
SigTerm

Reputation: 26439

Solution #1: use 1d array with size == dimension1*dimension2*dimension3*.... and emulate multidimensional array like that. You will have to write your own resize code (should be easy)
Solution #2: Use sparse array. A std::map<Coordinate, Value> will do.
Solution #3: Boost.MultiArray.
Solution #4: Don't store the world as N-dimensional array. Store objects as a list/deque/whatever, then use BSP tree, oct-trees, sweep and prune or space partitioning to quickly locate objects in visible area.

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96187

Don't store it as an array, use a structure containing the coords and the value.

Then store those objects in a smarter structure - deque, list or tree depending on how they need to be searched.

Upvotes: 4

Related Questions