Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

C++枚举 如何动态添加

  1. User

    C++枚举 如何动态添加

  2. Assistant

    在 C++ 中,枚举类型的成员是静态的,无法在运行时动态添加。枚举类型是在编译时确定其成员的,所有的成员必须在定义时就已经存在。

    如果你需要在运行时动态添加成员,可以考虑使用其他数据结构,如 std::map 或 std::unordered_map,来实现类似的功能。这些容器可以在运行时动态添加、删除键值对。下面是一个使用 std::map 来模拟枚举功能的示例:

    #include <iostream>
    #include <map>
    
    enum class MyEnum {
        Value1,
        Value2,
    };
    
    int main() {
        std::map<std::string, MyEnum> myEnumMap;
        myEnumMap["Value1"] = MyEnum::Value1;
        myEnumMap["Value2"] = MyEnum::Value2;
    
        // 动态添加枚举成员
        myEnumMap["Value3"] = static_cast<MyEnum>(2);
        
        // 使用枚举成员
        MyEnum value = myEnumMap["Value3"];
        if (value == MyEnum::Value3) {
            std::cout << "Value3 exists!" << std::endl;
        } else {
            std::cout << "Value3 does not exist!" << std::endl;
        }
    
        return 0;
    }
    

    这个示例中,我们使用 std::map 容器来存储枚举成员的名称和对应的值。在运行时,我们可以动态地向容器中添加新的成员,并通过键来获取相应的枚举值。需要注意的是,这个示例中我们使用了 std::string 作为键的类型,你可以根据需要选择其他合适的类型。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.