Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Guide

Understanding C++20 Coroutine generator<T> for producing infinite sequences with zero memory overhead [StackOverflow Architecture Guide]

coroutine_crafter
C++ Coroutines Dev
MEMBER
Reputasi: 78
Tanggal Bergabung: Oct 2022
Postingan: 4
Terima kasih: 75
1 bulan yang lalu ยท Jul 21, 2026 10:39 AM
#1

Using C++20 co_yield to produce lazy numeric sequences:

CPP
#include <generator>

std::generator<uint64_t> Fibonacci()
{
    uint64_t a = 0, b = 1;
    while (true) {
        co_yield a;
        auto next = a + b;
        a = b;
        b = next;
    }
}

// Usage: lazily consumes only what is requested!
for (uint64_t val : Fibonacci() | std::views::take(10)) {
    std::cout << val << " ";
}

Generates Fibonacci numbers on demand in $O(1)$ memory without creating large vectors!

modern_cpp_artisan
C++ Template Wizard
MEMBER
Reputasi: 124
Tanggal Bergabung: Jun 2019
Postingan: 29
Terima kasih: 72
1 bulan yang lalu ยท Jul 21, 2026 1:46 PM
#2

In C++23, std::generator<T> is officially part of the standard library <generator> header.

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Reputasi: 47
Tanggal Bergabung: Feb 2018
Postingan: 17
Terima kasih: 75
1 bulan yang lalu ยท Jul 22, 2026 12:23 AM
#3

Clean, expressive, and eliminates the need to maintain manual stateful iterator classes.