Is it possible to collect an iterator such that it populates a collection backwards, such as using push_front
in a VecDeque
?
It's possible to collect into a Vec
and then reverse it, but it seems like it should be unnecessary with data structures explicitly supporting this capability. I'd like to avoid writing an explicit for
loop if possible.
Yes, it's possible:
You just need a bit of glue code:
And implement it efficiently for various types:
Someone has to write that code.
Yes it is. You can iterate over your iterator with
for_each
and populate yourVecDeque
like this:You can reverse your iterator with the
rev
method. After that, you can callfor_each
to iterate it in the reverse order or you can collect it to aVec
directly since it is already reversed.Or more idiomatically you can directly reverse it in your
for
loop:Your output will be:
Playground