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

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

问题描述

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

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

MyMapType[,,] map; 

我使用固定数组而不是集合的原因是固定数组的工作速度要快得多.

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?

我考虑的另一个解决方案是滚动我自己的",其中您有一个二维数组字典,其中 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.

推荐答案

用一个类替换你的数组:

replace your arrays with a class:

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天全站免登陆