简体   繁体   中英

Access Array with an Array of Indices

I wondered, if it was possible to access a specific element of a multidimensional array using an array, rather than multiple integers.

Like for example:

int[,] map = sampleMap;
int[] position = { 1, 2 };

sampleObject = map[position]; // This line won't work. "cannot implicitly convert type 'int[]' to 'int'"

Instead of:

sampleObject = map[position[1], position[2]]

Of course, when working with only 2 dimensions, it wouldn't be much of a problem, but imagine I had many dimensions, like 10:

map[position[1], position[2], position[3], ..., position[10]]

It would be much nicer and more elegant, to just write:

map[position]

I've been looking around, but the best I found was "How to access Arrays in [insert programming language here]" or "how to access elements from [insert Array type here]" or things like that.

Here's a thought :

Assume your array contains 20 rows and 20 columns.

Lets say, you want to access the 26th element in your map (from the beginning of the map, top down left to right),

So, your coordinate function accepts 26 as a parameter, and,

26 / 20 = 1
26 % 20 - 1 = 5

translates map[26] to map[1, 5] , returning it's value

Not too sure if this will be helpful to you, just a thought!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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