c++ - 是否可以从函数的循环中返回多个值? C++

标签 c++ function loops

是否有可能从函数内的循环中返回许多值,类似于以下内容:

float MyFunc(float First, float Second)
{
    while (First < Second)
    {
        First++;
        return First;
    }
}

然后能够打印出返回的不同值?

(我知道这不是做任何事情的好方法,但我只是好奇,似乎找不到具体的好答案。也许我只是不够努力)

最佳答案

使用协程(在 Visual Studio 2015 Update 3 下工作)它看起来像这样:

generator<float> MyFunc(float First, float Second) {
  while (First < Second) {
      First++;
      co_yield First;
  }
}

然后你可以写

for (auto && i : MyFunc(2,7)) { std::cout << i << "\n"; }

Youtube 上有关于此的讨论:https://www.youtube.com/watch?v=ZTqHjjm86Bw

请参阅此处了解您的示例:https://youtu.be/ZTqHjjm86Bw?t=40m10s

如果您不想等待协程,请查看 boost::range 库。

或者实现你自己的迭代器

struct counter {
  counter (int first, int last) : counter {first, last, first} {}
  counter begin () const { return counter {first, last, first}; }
  counter end () const { return counter {first, last, last}; }
  int operator++ () { ++current; }
  int operator* () const { return current; }
private:
  counter (int first, int last, int current)
    : first (first), last (last), current (current)
    {}
  int first, last, current;
};

bool operator != (counter a, counter b) { return *a != *b; }

int main() {
    for (auto && i : counter {2,5}) { std::cout << i << "\n"; }
    return 0;
}

关于c++ - 是否可以从函数的循环中返回多个值? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702987/

相关文章:

c++ - malloc 的不常见使用

javascript - 函数没有返回任何值

c - 为第 4 个字母停止的循环

python - python mako 模板是否支持循环上下文中的 connitue/break?

javascript - 使用自定义过滤器 angularjs 过滤 2 个属性

c++ - boost::process::env 在 ubuntu 19.04 上损坏了?

c++ - 错误 :a nonstatic member reference must be relative to a specific object

c++ - 将 ASM jmp 内联到新内存

python - 将 pandas 中的字典拆分为单独的列

C++ 将双参数解析为字符串?