gpt4 book ai didi

c++ - 在 C++ 非 void 函数中使用 throw 替换 return

转载 作者:IT老高 更新时间:2023-10-28 13:57:47 27 4
gpt4 key购买 nike

在 C++ 函数中,将 return 替换为 throw 是一种好习惯吗?例如,我有以下代码

// return indices of two numbers whose sum is equal to target
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=0; i<nums.size()-1; ++i)
for(int j=i+1; j<nums.size(); ++j)
{
if(nums[i] + nums[j] == target) return vector<int>{i, j};
}
// return vector<int>{};
throw "no solution";
}

上面的代码用我的 GCC 7.2 编译。

最佳答案

In C++ functions, is it a good practice to replace return with throw?

return 不是可以用 throw 代替的东西一般来说

在您没有什么可返回的特殊情况下,抛出异常可能是退出函数的有效方式。

是否是“良好做法”,什么情况是“异常(exception)”都是主观的。例如,对于像您这样的搜索功能,可能没有解决方案也就不足为奇了,我认为抛出是不合适的。

通常还有其他的 throw 方式。将您的算法与返回子字符串开头索引的 std::string::find 之类的算法进行比较。如果子字符串不存在,它返回一个“非值”std::string::npos。您可以执行相同的操作并决定在未找到结果时返回索引 -1。在没有任何现有表示可以为此目的保留的情况下,还有一种通用方法可以将非值表示添加到类型:std::optional

附: vector 可能不是返回一对数字的好选择。 std::pair 可能会更好,或者如果您有好的数字名称,则可以使用自定义类。

关于c++ - 在 C++ 非 void 函数中使用 throw 替换 return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54713231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com