【提高效率】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;
}
相关推荐
布莱克6054 小时前
C++拷贝构造与拷贝赋值运算符的区别详解
开发语言·c++
啦啦啦啦啦zzzz5 小时前
时间轮定时器
linux·服务器·网络·c++·定时器
此生决int6 小时前
深入理解C++系列(15)——AVL树
开发语言·c++
一只旭宝6 小时前
预约系统版本2(pyhton+flask可视化版本)
服务器·数据库·c++·笔记·python·flask
爱奥尼欧6 小时前
10.C++ string 实现详解
java·开发语言·c++
会周易的程序员7 小时前
软件接入大模型实现 Agent —— 从原理到 C++ 落地完全指南
c++·人工智能·物联网·架构·agent·工业协议·mcp
hetao17338377 小时前
2026-08-21~23 hetao1733837 的刷题记录
c++·算法
Brilliantwxx10 小时前
【Linux】 进程(5) 僵尸进程与内存泄漏扩展
linux·运维·服务器·网络·c++
程与留10 小时前
08_对话框系统全解析——模态非模态、QMessageBox、QFileDialog
c++·qt
程序员的园10 小时前
赋值运算符为什么要避免自赋值?
c++