Consider:
enum Test
{
a = 3,
b = 7,
c = 1
};
I want to access the enum using an index. Something like this:
for (i=0; i<n; i++)
doSomething((Test)i);
How can I do something like this, where I will be able to access the enum using an index, though the members of the enum have different values?
Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.
Enum, array indexes. An enum array has many uses. It can be accessed with enum values. This example shows how to index an array of values with enum keys.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.
This is the best you can do:
enum Test { a = 3, b = 7, c = 1, LAST = -1 };
static const enum Test Test_map[] = { a, b, c, LAST };
for (int i = 0; Test_map[i] != LAST; i++)
doSomething(Test_map[i]);
You have to maintain the mapping yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With