我注意到生成器函数返回一个具有 .begin() 和 .end() 方法的对象。所以我尝试使用迭代器的经典语法:
for (auto it = x.begin(), end = x.end(); it != end; ++it) { /**/ }
但我注意到它不起作用......这是我的代码:
#include <experimental\generator>
using namespace std;
experimental::generator<int> test() {
co_yield 0;
}
int main() {
/*/
// THIS LOOP MAKES PROGRAM CRASH
for (auto it = test().begin(), end = test().end(); it != end; ++it)
int a = *it;
/*/
// THIS LOOP WORKS
for (auto i : test())
int a = i;
/**/
return 0;
}
关于生成器循环和迭代器语法,有什么我不知道的吗?有没有办法在生成器中使用迭代器语法?
感谢解答!
最佳答案
正如 Caramiriel 和 Some Programer Dude 所注意到的,我对生成器进行了两次实例化。以下循环有效:
auto gen = test();
for (auto it = gen.begin(), end = gen.end(); it != end; ++it)
int a = *it;
关于c++ - 使用迭代器语法循环 VS 使用生成器语法循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570219/