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

如何判断C++中System对象的actions仅包含特定元素?

判断system中actions是否为同一类型的实现方案

核心思路

先获取system.actions中第一个元素的类型,再遍历剩余元素检查是否全部与该类型一致,最后根据结果分支执行逻辑。同时要先处理actions为空的情况,避免程序出错。

代码实现示例

for (event::System system : Ev->getSys())
{
    // 先处理actions为空的情况,避免后续访问空容器出错
    if (system.actions.empty())
    {
        // 可根据需求跳过或执行空容器对应的逻辑
        continue;
    }

    // 获取第一个action的类型(假设Action类有type成员存储RUN/STOP等枚举值)
    auto first_type = system.actions.front().type;
    bool all_same = true;

    // 遍历所有action,检查是否全部和第一个类型一致
    for (const event::Action& action : system.actions)
    {
        if (action.type != first_type)
        {
            all_same = false;
            break; // 发现不同类型直接跳出循环,提升效率
        }
    }

    // 根据判断结果执行不同逻辑
    if (all_same)
    {
        // 所有action都是同一类型,可进一步判断具体是哪种类型
        if (first_type == event::ActionType::RUN)
        {
            // 仅包含RUN(多个RUN也符合)时执行的代码
        }
        // 如果需要处理其他单一类型,比如全是STOP,可添加else if分支
        // else if (first_type == event::ActionType::STOP) { ... }
    }
    else
    {
        // 包含多种不同类型时执行的逻辑
    }

    // 你原来的嵌套循环和switch逻辑可以放在这里
    for (event::Action action : system.actions)
    {
        switch (action.type) // 这里替换成你实际要判断的变量,原代码的thing可能是笔误
        {
            // 原有的case分支
            case event::ActionType::RUN:
                // ...
                break;
            case event::ActionType::STOP:
                // ...
                break;
            // 其他case
        }
    }
}

关键说明

  • 空容器检查:必须先判断system.actions.empty(),否则调用front()会触发未定义行为。
  • 效率优化:遍历过程中一旦发现不同类型就break,不用遍历完所有元素。
  • 类型判断:示例中假设Action类有type成员,且RUN/STOP是event::ActionType枚举的取值,如果你的类型判断方式不同(比如通过其他成员或方法),替换成对应的判断逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:11:07