Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through non-consecutive enum elements in c++

Tags:

c++

enums

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}
like image 828
stackunderflow Avatar asked Jul 22 '13 10:07

stackunderflow


People also ask

Can you iterate through an enum in C?

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.

Can you iterate through an enum?

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.

What is typedef enum in C?

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 iterate through an enum class C ++?

Can you loop through an enum C ++? Yes. It iterates over an std::initializer_list<Item>.


2 Answers

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
like image 113
Mats Petersson Avatar answered Sep 28 '22 18:09

Mats Petersson


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.

like image 35
Angew is no longer proud of SO Avatar answered Sep 28 '22 18:09

Angew is no longer proud of SO