I am wondering how efficient the std::generator
added in cpp23 standard, is going to compare with views. For example:
std::generator<int> f()
{
int i = 10;
while(true} {
co_yield i; ++i;
}
}
void use()
{
auto g {f()};
for (auto i = 0zu; i !=9; ++i)
{
std::cout << *g;
// not sure what the syntax is here...
++g;
}
}
vs
void use()
{
auto r = std::views::iota(10);
auto itr = r.begin();
for (auto i = 0zu; i != 9; ++i)
{
std::cout << *itr;
itr = std::next(itr);
}
}
Which one, in theory could be more efficient, and what, if any, makes their efficiency different?
(Forgive my badly crafted toy example. One difference between using generator and the view is that the generator's state will not be able to be cleared(? I am speculating here. Correct me if I am wrong.) But for the sake of the comparison just assume use
will only be called once, in both cases.)
Welcome any input or edit to the question/example as you see fit too!
std::generator
has anoperator<<
overload. If it does, it would probably extract values until the generator is exhausted. Which you would then do 10 times. Unlike theiota
example, where you only iterate over the range once. – Dye