How can I populate a vector in reverse?

Viewed 1306

I've got a vector:

let v = Vec<T>::with_capacity(10);

I want to populate it with data, in reverse order:

let i = 10;
while i > 0 {
    i -= 1;
    v[i] = non_pure_function(i);
}

Unfortunately, this panics; when allocating with Vec::with_capacity, the actual initial length of the vector is still 0.

How can I best accomplish this? What if I have no constructor for T?

1 Answers

How can I Populate a vector in reverse?

You can do it with VecDeque:

use std::collections::VecDeque;

fn main() {
    let mut v = VecDeque::new();

    for i in 0..5 {
        v.push_front(i);
    }

    for item in v {
        print!("{}", item);
    }
}

Playground


Instead of using VecDeque you can solve this problem with using array and the iterator:

  • Declare an array containing Option types.
  • Set array cells with the indexes.
  • Iterate over your array.
  • Filter your array to eliminate None values
  • Map the unwrapped values
  • Collect them into vector.
fn main() {
    let mut v = [None; 10];
    let mut i = 5i32;

    while i > 0 {
        i -= 1;
        v[i as usize] = Some(4i32 - i);
    }

    let reverse_populated: Vec<i32> = v
        .iter()
        .filter(|x| x.is_some())
        .map(|x| x.unwrap())
        .collect();

    for item in reverse_populated {
        print!("{:?}", item);
    }
}

Playground


Both output will be: 43210

Related