There are many ways to iterate through consecutive enums like
enum Animal {Cat, Dog, Dolphin}
But is there a convenient and easy way to iterate through non-consecutive enum elements like
enum Animal {Cat = 0, Dog = 5, Dolphin = 8}
you can iterate the elements like: for(int i=Bar; i<=Last; i++) { ... } Note that this exposes the really-just-an-int nature of a C enum. In particular, you can see that a C enum doesn't really provide type safety, as you can use an int in place of an enum value and vice versa.
To iterate through an enumeration, you can move it into an array using the GetValues method. You could also iterate through an enumeration using a For... Each statement, using the GetNames or GetValues method to extract the string or numeric value.
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of integer values, and it provides meaningful names to these values. The use of enum in C makes the program easy to understand and maintain. The enum is defined by using the enum keyword.
Can you loop through an enum C ++? Yes. It iterates over an std::initializer_list<Item>.
The short answer to this is "no".
You could make a table animals
, and then use a range loop on animals
.
Here's a complete "demo":
#include <iostream>
using namespace std;
enum Animal {Cat = 0, Dog = 5, Dolphin = 8};
int main()
{
Animal animals[] = { Cat, Dog, Dolphin };
for(Animal a : animals) cout << a << endl;
}
The output will be:
0
5
8
You could also provide the necessary operator(s) for the enumeration:
enum Animal
{
Cat = 0
, Dog = 5
, Dolphin = 8
};
inline Animal& operator++ (Animal &x)
{
switch (x) {
case Cat:
x = Dog;
break;
case Dog:
x = Dolphin;
break;
case Dolphin:
default:
x = static_cast<Animal>(static_cast<int>(x) + 1);
break;
}
return x;
}
DTTO for postfix ++
, <
and anything else you need. Of course, you have to keep them in sync with the definition of the enumeration. Not really straightforward, but it is an option.
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