0

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!

10
  • 1
    Mostly a vector<vector<T> >. Commented Sep 29, 2013 at 18:58
  • @H2CO3 And how would I ideally keep track of the dimensions? Say my field at one point stretches from -101:-18 to 55:12 or something. How do I determine where the information to cell 0:0 is stored? Commented Sep 29, 2013 at 19:00
  • 1
    using a variable. Of type size_t or int or whatever. And vector knows its size. Commented Sep 29, 2013 at 19:04
  • @H2CO3: vector<t>(dimension1*dimension2*dimension3*dimension4...), actually. Commented Sep 29, 2013 at 19:28
  • @H2CO3: Less allocations, no memory fragmentation/overhead, simpler resize. Commented Sep 29, 2013 at 19:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Cool, I did not know about deques before, they sound pretty handy. Thx!
@LarsEbert if you are going to move in any direction (rather than just scroll in 1d) then look at trees.
Okay, I just googled "trees", I do not know what I expected... But seriously, I understandy the definition of a (binary-)tree but I have no idea how to store the world in a tree.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.