1

I want to get the enum value in a for loop, by appending a number, like

enum example
{
Example_1,
Example_2,
Example_3,
.
.
.
Example_n
};
example x;
for (i = 0; i < n; i++
{x = Example_ + i; // if i = 5, I need Example_5
}

I want this implementation in C++11

Lundin
  • 195,001
  • 40
  • 254
  • 396
Naren
  • 23
  • 3

2 Answers2

2

If you have an Example_0 in the enum, then Example_0 + 5 will give you an integer value equivalent to Example_5. Enums are just integers.

All this assuming that you don't explicitly assign a value to a certain enumeration constant - that's another story.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • There are other enumrations in between, so I can use as you suggested. There is no proper offset between these specified enums – Naren May 08 '20 at 06:53
  • 1
    @Naren Then kindly _post the actual enum_ so that your question can be answered. – Lundin May 08 '20 at 06:54
  • The enumeration definition looks like: enum example { Example_1, Temp_0, Example_2, Temp_1, Temp_2, Apple_1, Example_3 } – Naren May 08 '20 at 07:05
0

You cannot concatenate name with number to retrieve enum name and use enum value.

  • With contiguous enum, you can use simple arithmetic.

  • you can create operator++ for your enum, resolve by switch:

    example operator++(example e)
    {
        switch (e) {
        case Example_1: return Example_2;
        case Example_2: return Example_3;
        case Example_3: return Example_4;
        // ...
        case Example_n: return Last;
        };
        throw std::runtime("value out of range");
    }
    

    and so, possibly

    for (example e = Example_1: e != Last; ++e) {/*..*/}

  • using array to provide enum list:

    constexpr auto AllExamples() {
        constexpr std::array res{{Example_1,
                                  Example_2,
                                  /*..*/,
                                  Example_n}};
        return res;
    }
    

    which allows:

    for (auto ex : AllExamples()) {/*..*/}
    f(AllExamples()[5]);
    
  • or use map if you really have to play with names:

    std::map<std::string, example> ExamplesAsMap() {
        return {
            {"Example_1", Example_1},
            {"Example_2", Example_2},
            /*..*/
            {"Example_n", Example_n},
            {"Value_1", Value_1},
            {"Value_2", Value_2},
            /*..*/
            {"Value_n", Value_n}
            /**/
        };
    }
    

    And then

    const auto m = ExamplesAsMap();
    example x;
    for (int i = 0; i < n; i++) {
        x = m.at("Example_" + std::to_string(i));
        // ...
    }
    
Jarod42
  • 203,559
  • 14
  • 181
  • 302