I am trying to populate a vector with a sequence of values. In order to calculate the first value I need to calculate the second value, which depends on the third value etc etc.
let mut bxs = Vec::with_capacity(n);
for x in info {
let b = match bxs.last() {
Some(bx) => union(&bx, &x.bbox),
None => x.bbox.clone(),
};
bxs.push(b);
}
bxs.reverse();
Currently I just fill the vector front to back using v.push(x)
and then reverse the vector using v.reverse()
. Is there a way to do this in a single pass?
The solution using
unsafe
is below. The unsafe version is slightly more than 2x as fast as the safe version usingreverse()
. The idea is to useVec::with_capacity(usize)
to allocate the vector, then useptr::write(dst: *mut T, src: T)
to write the elements into the vector back to front.offset(self, count: isize) -> *const T
is used to calculate the offset into the vector.If you don't mind adapting the vector, it's relatively easy.