IEnumerable<int>
现在,C ++ 20也获得了Coroutines。原则上,代码看起来非常相似:
#include <print>
#include <coroutine>
??? evenUpTo(int max) {
for (int i = 0; i < max; i += 2) {
co_yield i;
}
}
int main() {
for (auto e : evenUpTo(11)) {
std::print("{0}\n", e);
}
}
???
我读到C ++中不需要
元,因为C ++具有迭代器。一对迭代器(
.begin()
和.end()
)当然足以获得基于范围的循环工作。但是我会使用哪个容器?但是链接的问题是从2012年开始的,Coroutines来自C ++ 20,因此尚未涵盖此主题。
我可能可以编写自己的Generator<T>
模板,但是如果有内置的STL类型,我想避免。C++23
C++ 23现在具有
std::generator<>
#include <generator>
#include <print>
#include <coroutine>
#include <generator>
std::generator<int> evenUpTo(int max) {
for (int i = 0; i < max; i += 2) {
co_yield i;
}
}
int main() {
for (auto e : evenUpTo(11)) {
std::print("{0}\n", e);
}
}
Compiler Explorer:Https://godbolt.org/z/s66jbq9c7