tags:

views:

7694

answers:

6

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?

+3  A: 

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.

Corey Trager
+21  A: 

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.

andreas buykx
Note that, in the first part of the example, if you want to use 'i' as a Foo enum and not an int, you will need to static cast it like: static_cast<Foo>(i)
Clayton
A: 

C++ doesn't have introspection, so you can't determine this kind of thing at run-time.

David Kemp
+1  A: 

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....

João Augusto
+8  A: 

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.

Don Wakefield
Thanks for including useful links!
jwfearn
Glad to, @jwfearn!
Don Wakefield
+2  A: 

You can also overload the increment/decrement operators for your enumerated type.

JohnMcG