You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++17如何编写多条件简洁if语句(Scrabble分数计算场景)

方案1:静态查表法(推荐,性能最优)

因为字母ASCII码范围极小,预编译生成全局查找表是性能最高的实现方式,完全不需要运行时分支判断,代码简洁无冗余:

#include <cctype>
#include <string_view>

// C++17 constexpr lambda 编译期生成分值表,无运行时初始化开销
constexpr int scrabble_score[256] = []() constexpr {
    int arr[256] = {0};
    for (unsigned char c : "aeioulnrst") arr[c] = 1;
    for (unsigned char c : "dg") arr[c] = 2;
    for (unsigned char c : "bcmp") arr[c] = 3;
    for (unsigned char c : "fhvwy") arr[c] = 4;
    arr['k'] = 5;
    for (unsigned char c : "jx") arr[c] = 8;
    for (unsigned char c : "qz") arr[c] = 10;
    return arr;
}();

int calc_score(std::string_view word) {
    int score = 0;
    for (unsigned char ch : word) {
        // 自动兼容大小写输入,不需要可以去掉tolower逻辑
        score += scrabble_score[std::tolower(ch)];
    }
    return score;
}

方案2:C++17折叠表达式(贴合你想要的简洁多条件判断语法)

你期望的类似if(ch == a,e,i,l...)的写法,可以通过C++17新增的折叠表达式实现,完全不用写重复的||判断:

#include <cctype>
#include <string_view>

template<typename T, typename... Args>
constexpr bool is_one_of(T&& value, Args&&... options) {
    return (... || (value == options));
}

int calc_score(std::string_view word) {
    int score = 0;
    for (unsigned char ch : word) {
        unsigned char c = std::tolower(ch);
        if (is_one_of(c, 'a','e','i','o','u','l','n','r','s','t')) score +=1;
        else if (is_one_of(c, 'd','g')) score +=2;
        else if (is_one_of(c, 'b','c','m','p')) score +=3;
        else if (is_one_of(c, 'f','h','v','w','y')) score +=4;
        else if (c == 'k') score +=5;
        else if (is_one_of(c, 'j','x')) score +=8;
        else if (is_one_of(c, 'q','z')) score +=10;
    }
    return score;
}

方案3:string查找快速实现(不需要模板)

如果不想写模板代码,也可以用string_view的find方法判断字符归属:

#include <cctype>
#include <string_view>

int calc_score(std::string_view word) {
    int score = 0;
    for (unsigned char ch : word) {
        char c = std::tolower(ch);
        if (std::string_view("aeioulnrst").find(c) != std::string_view::npos) score +=1;
        else if (std::string_view("dg").find(c) != std::string_view::npos) score +=2;
        else if (std::string_view("bcmp").find(c) != std::string_view::npos) score +=3;
        else if (std::string_view("fhvwy").find(c) != std::string_view::npos) score +=4;
        else if (c == 'k') score +=5;
        else if (std::string_view("jx").find(c) != std::string_view::npos) score +=8;
        else if (std::string_view("qz").find(c) != std::string_view::npos) score +=10;
    }
    return score;
}

优先推荐使用查表法,性能最优且维护成本低;如果仅需要简化多条件判断写法,折叠表达式方案最贴合需求。

内容的提问来源于stack exchange,提问作者Carlos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:36:03