【提高效率】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;
}
相关推荐
c++之路10 小时前
CMake 系列教程(二):基础命令详解
开发语言·c++
南境十里·墨染春水14 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
一拳一个呆瓜18 小时前
【STL】_SCL_SECURE_NO_WARNINGS
c++·stl
小小编程路18 小时前
C++ 异常 完整讲解
开发语言·c++
Frank学习路上21 小时前
【C++】面试:关键字与语法特性
c++·面试
Irissgwe1 天前
数据结构-栈和队列
数据结构·c++·c·栈和队列
点云侠1 天前
PCL 生成三棱锥点云
c++·算法·最小二乘法
.道阻且长.1 天前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
laplaya1 天前
使用 vcpkg 管理 C++ 项目中的依赖
开发语言·c++
blueman88881 天前
VS2022 切换定义(F12 / Go to Definition)反应慢
c++·visual studio