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

C++中vector不可为NULL,除空vector外该返回何种替代值?

解决C++ how_sum函数中target_sum<0的返回值问题

因为std::vector<int>无法返回NULL,且空vector已被用于表示target_sum=0的合法情况,这里有几种实用的替代方案:

方案1:使用可选类型(C++17及以上)

返回std::optional<std::vector<int>>,这样当target_sum<0时可以返回std::nullopt,明确表示"无有效结果",空vector依然保留为target_sum=0的返回值。修改后的函数签名和关键代码如下:

#include <optional>

std::optional<std::vector<int>> how_sum(long target_sum, std::vector<int> numbers, std::map<int, std::optional<std::vector<int>>> &memo)
{
    // ...

    if (target_sum == 0)
        return std::vector<int>{};    // 返回空vector表示成功匹配

    if (target_sum < 0)
        return std::nullopt;          // 表示无有效结果

    // ...
}

方案2:通过输出参数传递结果,函数返回布尔值

把原本要返回的vector改成函数的引用参数,函数返回bool来标识是否成功:

  • 返回true表示找到有效组合(包括target_sum=0的空vector情况)
  • 返回false表示target_sum<0或无匹配组合

修改后的代码示例:

bool how_sum(long target_sum, std::vector<int> numbers, std::vector<int> &result, std::map<int, bool> &memo)
{
    // ...

    if (target_sum == 0) {
        result.clear();  // 空vector对应target_sum=0
        return true;
    }

    if (target_sum < 0)
        return false;    // 无有效结果

    // ... 逻辑处理,找到组合后填充result并返回true
}

方案3:使用特殊标记值

可以约定一个特殊的vector作为"无效"标识,比如在vector中插入一个不可能出现在输入numbers中的值(比如INT_MIN)。但这种方式需要额外的检查逻辑,且存在误判风险,仅适合无法使用前两种方案的场景:

#include <climits>

std::vector<int> how_sum(long target_sum, std::vector<int> numbers, std::map<int, std::vector<int>> &memo)
{
    // ...

    if (target_sum == 0)
        return {};

    if (target_sum < 0)
        return {INT_MIN};  // 用INT_MIN作为无效标记

    // ... 后续逻辑中需要先检查返回的vector是否包含这个标记
}

优先推荐方案1(C17+),它的语义最清晰,能明确区分"空组合(target_sum=0)"和"无有效结果(target_sum<0)"两种场景;如果项目不支持C17,方案2是更安全的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:57:21