I have an enum class, now I want to turn them into array, so that any given enum I could return the corresponding object like below:
PeopleInfo fetch(enum e) {
return arr[e];
}
Sounds easy, 1-1 mapping would do the trick, but today my enum is relative large and sparse like
enum class People: {
American_start = 0x0,
John,
Aaron,
...
Asian_start = 0x10000,
Yen_Huan,
Kang_Hsuan,
European_start = 0x20000,
...
}
As you can see, in order to preserve the space for additional people to join in the future, these enum apparently cannot use 1-1 mapping here, that's just a total waste of memory, what I need is an array with size of all people listed, so I can get the info I want
Does anybody has good idea how to do so?
CodePudding user response:
You can create an index that isn't sparse, so that you can use an array that doesn't have any holes in it.
PeopleInfo fetch(enum e) {
index = e;
if (index >= European_start)
index -= European_start - Asian_end;
if (index >= Asian_start)
index -= Asian_start - American_end;
if (index >= American_start)
index -= American_start;
return arr[index];
}
CodePudding user response:
You can use a 2D-array where the columns are the continents. Then you can identify the continent by the upper bytes and objects by the lower bytes.
SomeObject arr[NUMBER_OF_CONTINENTS][MAX_NUMBER_OF_OBJECTS];
PeopleInfo fetch(enum e) {
return arr[e >> 16][e & 0xffff];
}
Note: You might waste some memory, when one continent has a lot more objects than the others.