TL; DR: does std or any crate (like itertool) have a collect_backward()
for ExactSizeIterator
?
I have a piece of code that look more or less like:
let it: impl ExactSizeIterator<Item=T> = ...;
let mut my_vec: Vec<T> = it.collect();
my_vec.reverse();
This could be desugared to:
let mut my_vec: Vec<T> = Vec::with_capacity(it.len());
while let Some(elem) = it.next() {
my_vec.push(elem); // insert elements from the front
}
my_vec.reverse();
Would it be possible to directly create the vector by inserting the elements from the end. Somethings like an hypothetical.
let my_vec = it.collect_backward();
Since it
is ExactSizeIterator
, it is possible to create the Vec
with the right size, and then use indices to fill directly the right cell.
let mut my_vec = Vec::with_capacity(it.len());
my_vec.resize(it.len());
for i in (0..it.len()).rev {
my_vec[i] = it.next(); // insert elements from the back
}
assert_eq!(it.next(), None);