【提高效率】C++使用map替代传统switch case

switch case示例

c 复制代码
enum class ENTestType
{
    first = 1,
    second,
    third,
    forth
};

class Test
{
public:
    void testFun(ENTestType type)
    {
        switch (type)
        {
        case ENTestType::first:
            std::cout << "first" << std::endl;
            break;
        case ENTestType::second:
            std::cout << "first" << std::endl;
            break;
        case ENTestType::third:
            std::cout << "third" << std::endl;
            break;
        case ENTestType::forth:
            std::cout << "forth" << std::endl;
            break;
        default:
            break;
        }
    }
};

int main()
{
    auto t = std::make_unique<Test>();
    t->testFun(ENTestType::first);
    return 0;
}

使用map替代switch:

cpp 复制代码
class Test
{
public:
    Test()
    {
        _testMap[ENTestType::first] = []{
            std::cout << "first" << std::endl;
        };
        _testMap[ENTestType::second] = []{
            std::cout << "second" << std::endl;
        };
        _testMap[ENTestType::third] = []{
            std::cout << "third" << std::endl;
        };
        _testMap[ENTestType::forth] = []{
            std::cout << "forth" << std::endl;
        };
    }
public:
    std::map<ENTestType, std::function<void()>> _testMap;
};

int main()
{
    auto t = std::make_unique<Test>();
    t->_testMap[ENTestType::first]();
    return 0;
}
相关推荐
不会就选b35 分钟前
C++补充部分(一)--lambda 表达式
开发语言·c++
丰色木夕8 小时前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
衍玊11 小时前
多路转接原理与应用
c++
himobrinehacken12 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
Android小码家15 小时前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle
hetao173383715 小时前
2026-10-19 hetao1733837 的刷题记录
c++·算法
夏虫不可与之言冰15 小时前
第三课 点亮 LED 与定时器非阻塞闪烁
c语言·c++·vscode·单片机·嵌入式硬件·物联网
辛苦才能15 小时前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
miller-tsunami15 小时前
STL简介&string相关知识点
开发语言·c++·string
坤坤子吖16 小时前
Linux 线程同步与互斥——互斥锁
linux·服务器·c++·笔记·学习