有没有可能将 for 循环结果返回到像三元运算符这样的函数中?

Roh*_*ari 0 c++

到目前为止,我们已经看到了三元运算符的工作原理:

return (x == y) ? x : y; ' If x equals to y, then return x, otherwise y
Run Code Online (Sandbox Code Playgroud)

替代代码可以写成如下:

if (x == y)
    return x;
else
    return y;
Run Code Online (Sandbox Code Playgroud)

问题是,是否可以使用带有 For 循环的 return 语句返回 N 个数字的总和?

此问题的说明性示例:

#include <iostream>

int forLoop(int);

int main(void)
{
    std::cout << "Sum of 1 + 2 + 3: " << forLoop(3);

    return 0;
}

int forLoop(int x) {
    int sum = 0;

    return (for (int i = 1; i <= x; i++) sum += i);
    // Expecting to return (1 + 2 + 3 = 6) to the function using loop and return.
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

main.cpp: In function ‘int forLoop(int)’:
main.cpp:14:13: error: expected primary-expression before ‘for’
     return (for (int i = 1; i <= x; i++) sum += i);
             ^~~
main.cpp:14:13: error: expected ‘)’ before ‘for’
main.cpp:14:29: error: ‘i’ was not declared in this scope
     return (for (int i = 1; i <= x; i++) sum += i);
                             ^
Run Code Online (Sandbox Code Playgroud)

有什么可能的方法可以在一行中而不是:

int forLoop(int x) {
    int sum = 0;

    for (int i = 1; i <= x; i++)
        sum += i;
    return sum;
}
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 5

您可以使用自然数之和的封闭形式:

int forLoop(int n)
{
  return n * (n + 1) / 2;
}
Run Code Online (Sandbox Code Playgroud)

这没有for循环。

有了range-v3你可以这样做:

int forLoop(int n)
{
  return ranges::accumulate(ranges::views::iota(1, n + 1), 0);
}
Run Code Online (Sandbox Code Playgroud)

for这里也没有循环。

为完整起见,避免循环的标准方法将涉及使用算法,如评论中所指出的。这可能看起来像:

int forLoop(int n)
{
  std::vector<int> v;
  std::iota(v.begin(), v.end(), 1);
  return std::accumulate(v.begin(), v.end(), 1);
}
Run Code Online (Sandbox Code Playgroud)

当然,我不推荐最后一个选项,因为它不必要地分配O(n)空间并花费O(n)时间用于O(1)空间/时间算法。