#include <iostream>
#include <coroutine>
struct Generator {
struct promise_type;
using handle = std::coroutine_handle;
struct promise_type {
int current_value;
auto get_return_object() {
return Generator{handle::from_promise(*this)};
}
auto initial_suspend() { return std::suspend_always{}; }
auto final_suspend() noexcept { return std::suspend_always{}; }
void unhandled_exception() { std::terminate(); }
auto yield_value(int value) {
current_value = value;
return std::suspend_always{};
}
void return_void() {}
};
handle coro;
Generator(handle h) : coro(h) {}
~Generator() { coro.destroy(); }
int next() {
coro.resume();
return coro.promise().current_value;
}
};
Generator sequence() {
for (int i = 0; i < 5; ++i) {
co_yield i;
}
}
int main() {
auto gen = sequence();
for (int i = 0; i < 5; ++i) {
std::cout << gen.next() << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?