带有负索引的数组 [英] Array with negative indexes

查看:70
本文介绍了带有负索引的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,用于存储我正在开发的游戏的地图数据.

I have an array which I'm using to store map data for a game I'm working on.

MyMapType[,,] map; 

我使用固定数组而不是Collection的原因是因为固定数组的运行速度非常快.

The reason I'm using a fixed array instead of a Collection is because fixed arrays work very much faster.

现在我的问题是,我想在游戏中支持负z级别.因此,我希望能够访问一个负索引.

Now my problem is, I'd like to have support for negative z levels in the game. So I'd like to be able to access a negative index.

如果这不可能,我想到了另外两个解决方案.

If this is not possible, I thought of a pair of other solutions.

我当时正在考虑将地平面设置为某个任意数字(例如10),而任何小于10的东西都可以视为负数.但是,如果不使用数组,这会不会使数组变大10倍而没有任何结果呢?

I was thinking as a possible solution to have ground-level as some arbitrary number (say 10), and anything less than 10 could be considered negative. But wouldn't this make the array 10 times larger for nothing if its not in use?

我考虑的另一种解决方案是滚动我自己的",其中您拥有2D数组的字典,而Z级别作为索引保留在列表中.但这还有很多工作要做,我不确定它是否慢.

Another solution I considered was to 'roll my own' where you have a Dictionary of 2D arrays, with the Z level held in the List as the index. But this is a lot more work and I'm not sure if its slow or not.

所以总结一下-创建支持负索引的数组的任何方法是什么?如果没有的话,有没有一种干净的方法可以在不牺牲CPU时间或RAM的情况下模仿"这种行为,请注意,这些游戏地图可能最终会占用很大的空间,因此需要不断对其进行访问.

So to summarise - any way of creating an array which supports a negative index? And if there's not - is there a clean way of 'emulating' such behaviour without sacrificing too much CPU time or RAM - noting that these are game maps which could end up large AND need to be accessed constantly.

推荐答案

将数组替换为类:

class MyArray {
    private MyMapType[] myArray = new myMapType[size]
    MyMapType this[index] {
       get{return myArray[index + offset];}
    }

}

您可以在构造函数中设置大小和偏移量,甚至可以随意更改它.

you can set the size and the offset in the constructor or even change it at will.

在此示例的基础上,是另一个版本:

Building on this example here is another version:

class MyArray {
    private MyMapType[] positives = new myMapType[size]
    private MyMapType[] negatives = new myMapType[size-1]
    MyMapType this[index] {
       get{return index >= 0 ? positives[index] : negateves[1-index];}
    }

}

这并没有改变您需要为它们两者设置大小的事实.老实说,我喜欢第一个更好的

It does not change the fact that you need to set the size for both of them. Honestly I like the first one better

这篇关于带有负索引的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆