【提高效率】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;
}
相关推荐
云泽80810 分钟前
从零吃透 C++ 异常:抛出捕获、栈展开、异常重抛与编码规范详解
开发语言·c++·代码规范
REDcker18 分钟前
libdatachannel 快速入门
c++·webrtc·datachannel
second602 小时前
第一部分:快速上手 —— 建立 C++ 基本语法与编程范式
开发语言·c++
郝学胜-神的一滴2 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
bksczm2 小时前
linux之线程概念和控制
linux·开发语言·c++
hehelm3 小时前
Linux网络编程—TCP字典翻译系统
linux·开发语言·网络·c++·tcp/ip
hansang_IR3 小时前
【记录】「SCOI2016」三道模拟赛/26.7.12
c++·算法
会周易的程序员4 小时前
从零构建多核CPU负载自适应控制系统
linux·c++·笔记·物联网·测试工具
程序猿编码4 小时前
用C++从零开始造一个微型GPT,不借助任何第三方库
开发语言·c++·gpt·模型推理
qz5zwangzihan15 小时前
题解:Atcoder Beginner Contest abc466 F - Many Mod Calculation
c++·题解·优先队列·atcoder·大根堆·abc466·abc466f