【问题标题】:Appending a number to enum to get other enum将数字附加到枚举以获取其他枚举
【发布时间】:2020-05-08 06:21:18
【问题描述】:

我想在 for 循环中获取枚举值,方法是附加一个数字,例如

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
}

我想要 C++11 中的这个实现

【问题讨论】:

  • 不要使用枚举,使用数组。
  • 你问的是C还是C++?
  • 我已经有了在我的代码库中广泛使用的枚举。所以不能改成数组。
  • 我要求 c++ 实现

标签: c++ c++11 enums enumeration


【解决方案1】:

如果枚举中有一个Example_0,那么Example_0 + 5 会给你一个等于Example_5 的整数值。枚举只是整数。

所有这一切都假设您没有明确地为某个枚举常量赋值 - 那是另一回事。

【讨论】:

  • 中间还有其他枚举,所以我可以按照你的建议使用。这些指定的枚举之间没有适当的偏移量
  • @Naren 那么请发布实际的枚举,以便您的问题得到解答。
  • 枚举定义如下: enum example { Example_1, Temp_0, Example_2, Temp_1, Temp_2, Apple_1, Example_3 }
【解决方案2】:

您不能将名称与数字连接以检索枚举名称并使用枚举值。

  • 使用连续枚举,您可以使用简单的算术。

  • 您可以为您的枚举创建operator++,通过开关解决:

    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");
    }
    

    所以,可能

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

  • 使用数组提供枚举列表:

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

    允许:

    for (auto ex : AllExamples()) {/*..*/}
    f(AllExamples()[5]);
    
  • 如果你真的需要玩名字,也可以使用地图:

    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}
            /**/
        };
    }
    

    然后

    const auto m = ExamplesAsMap();
    example x;
    for (int i = 0; i < n; i++) {
        x = m.at("Example_" + std::to_string(i));
        // ...
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多