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

C++如何用for循环避免编写重复的带编号weight变量处理代码

C++ 重复逻辑优化方案

方案1:配置数组+循环实现(最推荐)

你认为for循环不适用属于常见误解,只需要把硬编码的编号、key值抽成配置数组即可,不需要单独定义带编号的变量:

// 替换ResultType为你的result变量的实际类型
#include <array>
#include <string_view>

// 预定义所有需要处理的组key
constexpr std::array<std::string_view, 3> kGroupKeys = {
    "w_group_1",
    "w_group_2",
    "w_group_3"
};

std::array<double, 3> weights;
std::array<std::string, 3> weight_bars;

for (size_t i = 0; i < kGroupKeys.size(); ++i) {
    weights[i] = result[kGroupKeys[i]];
    GetData(weights[i], weight_bars[i]);
    weight_bars[i] += " ";
}

后续如果需要使用原逻辑的weight1/weight_bar1,直接取weights[0]/weight_bars[0]即可,和单独定义变量的使用效果完全一致,后续要新增第4组只需要在kGroupKeys里加一行配置即可。

方案2:函数封装(适用于每组有定制需求的场景)

如果确实不想用循环,或者每组后续可能有独立的定制逻辑,可以把重复逻辑抽成公用函数:

// 替换ResultType为你的result变量的实际类型
std::string process_group(const ResultType& result, std::string_view key, double& out_weight) {
    out_weight = result[key];
    std::string weight_bar;
    GetData(out_weight, weight_bar);
    weight_bar += " ";
    return weight_bar;
}

// 调用代码精简为每行一组,没有重复逻辑
double weight1;
std::string weight_bar1 = process_group(result, "w_group_1", weight1);
double weight2;
std::string weight_bar2 = process_group(result, "w_group_2", weight2);
double weight3;
std::string weight_bar3 = process_group(result, "w_group_3", weight3);

选型建议

  • 组数量较多/后续可能新增组:优先选方案1,维护成本最低
  • 组数量固定且每组有独立定制逻辑:优先选方案2,可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:24:03