在C++中使用map来取代很多个if else和switch

在C++中使用map来取代很多个if else和switch

利用map中的key和value键值对来取代if else效率会好不少。

#include <iostream>
#include <map>
#include <functional>

using namespace std;

int fun1(int a,int b){ return  a + b;}
int fun2(int a,int b){ return  a - b;}
int fun3(int a,int b){ return  a * b;}
int fun4(int a,int b){ return  a / b;}

int main() {
    map<int,function<int(int,int)>> m_fun;
    /**相当于:
    if(key == 1){ fun1(6, 3);}
    if(key == 2){ fun1(6, 3);}
    if(key == 3){ fun1(6, 3);}
    if(key == 4){ fun1(6, 3);}
    **/
    m_fun.insert(make_pair(1,fun1));
    m_fun.insert(make_pair(2,fun2));
    m_fun.insert(make_pair(3,fun3));
    m_fun.insert(make_pair(4,fun4));
    int a[4] = {1,2,3,4};
    for(auto x : a)
    {
        cout<<m_fun[x](6,3)<<endl;
    }
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

第一次听说map的键值对用来替换很多if else和switch判断的时候,我很懵逼,map居然能和if else扯上关系????

去了解一下一下,好像在Java后端开发中,比如根据不同的抽奖卷去查询不同的数据库,抽奖卷类型很多,如果用if else来写,程序就会很长。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
引用\[1\]提到,如果一个switch语句包含超过5个情况,它会使用lookup table或hash list来实现。这意味着所有的情况都会在同一时间内被访问,相比之下,使用一连串的if语句,最后一个if的情况总是要花更多的时间才能被访问,因为必须要优先比较之前的所有if情况。\[2\]因此,如果情况较多,使用switch语句可能会更快。然而,如果只有几个情况,switch语句的速度可能不会有太大影响,可以使用if-else语句。另外,引用\[3\]提到,使用map的key和value键值对来取代if-else语句也可以提高效率。通过将不同情况的函数与对应的key值关联起来,可以通过查找key值来执行相应的函数,避免了多个if-else语句的嵌套。这种方法在处理多个情况时可以更加高效。 #### 引用[.reference_title] - *1* *2* [if和switch效率比较](https://blog.csdn.net/qq_35719728/article/details/110931252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [在C++使用map取代很多个if else和switch](https://blog.csdn.net/qq_41655797/article/details/124323500)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值