I just noticed that you can not use standard math operators on an enum such as ++ or +=
So what is the best way to iterate through all of the values in a C++ enum?
I just noticed that you can not use standard math operators on an enum such as ++ or +=
So what is the best way to iterate through all of the values in a C++ enum?
You can't with an enum. Maybe an enum isn't the best fit for your situation.
A common convention is to name the last enum value something like MAX and use that to control a loop using an int.
The typical way is as follows:
enum Foo {
One,
Two,
Three,
Last
};
for ( int foo = One; foo != Last; ++foo )
{
// ...
}
Of course, this breaks down if the enum values are specified:
enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.
switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
C++ doesn't have introspection, so you can't determine this kind of thing at run-time.
If your enum starts with 0 and the increment is always 1.
enum enumType
{
A = 0,
B,
C,
enumTypeEnd
};
for(int i=0; i<enumTypeEnd; i++)
{
enumType eCurrent = (enumType) i;
}
If not I guess the only why is to create something like a
vector<enumType> vEnums;
add the items, and use normal iterators....
One of many approaches: When enum Just Isn't Enough: Enumeration Classes for C++.
And, if you want something more encapsulated, try this approach from James Kanze.
You can also overload the increment/decrement operators for your enumerated type.