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

如何简化这段基于isActive的C++ if-else嵌套分支语句?

几种精简这段条件分支的方法

1. 合并条件+三元表达式

把嵌套的if拆成先判断columnId == 4,再用三元运算符选择要绘制的文本内容,直接减少一层嵌套:

if (columnId == 4) {
    g.drawText(isActive ? active[row].value : inactive[row].value, 
               2, 0, width, height, Justification::centredLeft, true);
}

2. 封装为复用函数

如果多处都有类似逻辑,直接封装成函数,避免重复代码:

// 可根据实际类型调整参数(比如替换ActiveItem/InactiveItem为你真实的容器元素类型)
void drawColumn4Text(Graphics& g, bool isActive, 
                     const std::vector<ActiveItem>& active, 
                     const std::vector<InactiveItem>& inactive, 
                     int row, int width, int height) {
    g.drawText(isActive ? active[row].value : inactive[row].value, 
               2, 0, width, height, Justification::centredLeft, true);
}

// 调用时只需一行
if (columnId == 4) {
    drawColumn4Text(g, isActive, active, inactive, row, width, height);
}

3. 用引用统一目标容器

如果active和inactive是同类型的容器,先通过引用绑定到目标容器,再进行绘制,可读性更好,后续若有其他操作也能复用这个引用:

if (columnId == 4) {
    auto& targetContainer = isActive ? active : inactive;
    g.drawText(targetContainer[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

这几种方法各有适用场景:第一种适合快速优化单处代码,第二种适合多处复用的场景,第三种在需要对目标容器执行更多操作时更实用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:48:14