c++ - 使用迭代器语法循环 VS 使用生成器语法循环

标签 c++ loops iterator generator

我注意到生成器函数返回一个具有 .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/

相关文章:

c# - Razor:在循环中添加变量而不显示它

c++ - VirtualAlloc 的困惑 - 它只适用于页面吗?

c++ - 操作系统何时关闭已连接的 UDP 套接字?

c++ - 微软 C++ 异常 : long at memory location

c - 在可变大小的井字棋网格中检查获胜的最有效方法?

javascript - 从函数生成模板文字的正确方法

c++ - 迭代器不能正常访问的问题

java - 使用迭代器删除时出现链接列表错误

java - 无法实例化类型 Iterator<ArrayList<Integer>>

c++ - 如何在 QStackedLayout 中居中小部件?