简体   繁体   English

C ++中的多维数组?

[英]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. 现在,我需要以某种二维数组存储有关世界细胞的信息,其中0:0是原始位置。 At the beginning of the game, I generate a small area of the world, say from -10:-5 to 10:5. 在游戏开始时,我产生了一个很小的区域,例如-10:-5至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! 再次感谢你的帮助!

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. 然后将这些对象存储在一个更智能的结构中,即双端队列,列表或树,具体取决于如何搜索它们。

Solution #1 : use 1d array with size == dimension1*dimension2*dimension3*.... and emulate multidimensional array like that. 解决方案1 :使用size == dimension1*dimension2*dimension3*.... 1d数组,并像这样模拟多维数组。 You will have to write your own resize code (should be easy) 您将必须编写自己的调整大小代码(应该很容易)
Solution #2 : Use sparse array. 解决方案2 :使用稀疏数组。 A std::map<Coordinate, Value> will do. 将执行std::map<Coordinate, Value>
Solution #3 : Boost.MultiArray . 解决方案3Boost.MultiArray
Solution #4 : Don't store the world as N-dimensional array. 解决方案#4 :不要将世界存储为N维数组。 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. 将对象存储为列表/双端队列/任何内容,然后使用BSP树,八叉树,扫描和修剪或空间分区快速在可见区域中定位对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM