【提高效率】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;
}
相关推荐
艾莉丝努力练剑38 分钟前
【C++模版进阶】如何理解非类型模版参数、特化与分离编译?
linux·开发语言·数据结构·c++·stl
草莓熊Lotso1 小时前
基于容器适配器模式的 Stack 与 Queue 实现:复用底层容器的优雅设计
c++·网络协议·rpc·适配器模式
立志成为大牛的小牛1 小时前
数据结构——二十五、邻接矩阵(王道408)
开发语言·数据结构·c++·学习·程序人生
qq_479875434 小时前
C++ std::Set<std::pair>
开发语言·c++
云知谷7 小时前
【C++基本功】C++适合做什么,哪些领域适合哪些领域不适合?
c语言·开发语言·c++·人工智能·团队开发
仰泳的熊猫7 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
^Moon^7 小时前
CycloneDDS:跨主机多进程通信全解析
c++·分布式·dds
C_Liu_9 小时前
C++:list
开发语言·c++
my rainy days10 小时前
C++:友元
开发语言·c++·算法
鄃鳕11 小时前
python 字典 列表 类比c++【python】
c++·python