是否有可能从函数内的循环中返回许多值,类似于以下内容:
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/