Home Ask Login Register

Developers Planet

Your answer is one click away!

Humam Helfawi February 2016

Iterate using an enum

I have std::map which its key is an enum like this:

enum class my_enum{a=1,b,c,d};
std::map<my_enum,my_class> my_map;

I want to iterate over the map so I used this for:

for (auto current_type = (id_type)0;
     (int)current_type < 4;
     current_type = (my_enum)((int)current_type + 1)){
   //do things

I think it is rubbish. Do you have a better suggestion?


I am totally aware of using of iterators. I know they are prefereable. However, for some reason, I have to stick to the regular index-based for.


Cheers and hth. - Alf February 2016

To iterate over a map m:

for( auto& item : m ) ...

To iterate over your enum class values:

#include <initializer_list>

enum class my_enum{a=1,b,c,d};

auto main() -> int
    using E = my_enum;
    for( my_enum const id : {E::a, E::b, E::c, E::d} ) {}


enum class my_enum{a=1,b,c,d};

auto main() -> int
    for( int i = int( my_enum::a ); i <= int( my_enum::d ); ++i )
        auto const id = my_enum( i );
        // ...

ams February 2016

Define your types like this:

enum class my_enum{a=1, b, c, d, END};
std::map<my_enum,my_class> my_map;

my_enum& operator++( my_enum &val ) {
  using IntType = typename std::underlying_type<my_enum>::type
  val = static_cast<my_enum>( static_cast<IntType>(val) + 1 );
  return val;

And then you can use them like this:

for (my_enum e = my_enum::a; e < my_enum::END; ++e) {
   my_class c = my_map[e];

(Although, you might prefer to use something other that operator[] if you don't want to create null-values for entries that don't exist.)

Post Status

Asked in February 2016
Viewed 3,529 times
Voted 11
Answered 2 times


Leave an answer

Quote of the day: live life