【提高效率】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;
}
相关推荐
博笙困了5 小时前
AcWing学习——双指针算法
c++·算法
感哥6 小时前
C++ 指针和引用
c++
感哥16 小时前
C++ 多态
c++
沐怡旸1 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4161 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥1 天前
C++ std::set
c++
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
博笙困了1 天前
AcWing学习——差分
c++·算法
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式