【提高效率】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;
}
相关推荐
黑不溜秋的19 分钟前
C++ 语言特性29 - 协程介绍
开发语言·c++
一丝晨光24 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
￴ㅤ￴￴ㅤ9527超级帅38 分钟前
LeetCode hot100---二叉树专题(C++语言)
c++·算法·leetcode
_GR1 小时前
每日OJ题_牛客_牛牛冲钻五_模拟_C++_Java
java·数据结构·c++·算法·动态规划
Death2001 小时前
Qt 中的 QListWidget、QTreeWidget 和 QTableWidget:简化的数据展示控件
c语言·开发语言·c++·qt·c#
六点半8881 小时前
【C++】速通涉及 “vector” 的经典OJ编程题
开发语言·c++·算法·青少年编程·推荐算法
coduck_S12004zbj2 小时前
csp-j模拟五补题报告
c++·算法·图论
Death2002 小时前
Qt 3D、QtQuick、QtQuick 3D 和 QML 的关系
c语言·c++·qt·3d·c#
sukalot2 小时前
windows C++-windows C++-使用任务和 XML HTTP 请求进行连接(二)
c++·windows
qianbo_insist3 小时前
simple c++ 无锁队列
开发语言·c++