Lesson 19 of 20
Vectors
Vectors
Vec<T> is Rust's growable array. It stores elements contiguously on the heap.
Creating Vectors
let empty: Vec<i32> = Vec::new();
let v = vec![1, 2, 3, 4, 5]; // macro shorthand
let zeros = vec![0; 10]; // ten zeros
Modifying Vectors
let mut v = Vec::new();
v.push(1);
v.push(2);
v.pop(); // removes last — returns Option<T>
v.insert(0, 99); // insert at index
v.remove(0); // remove at index
v.sort(); // sort in place
v.dedup(); // remove consecutive duplicates (sort first)
v.retain(|&x| x > 0); // keep elements matching predicate
v.extend([4, 5, 6]); // append elements
Accessing Elements
v[0] // panics if out of bounds
v.get(0) // returns Option<&T> — safe
v.first() // Option<&T>
v.last() // Option<&T>
Iteration
for x in &v { println!("{}", x); }
for x in &mut v { *x *= 2; }
for x in v { /* consumes v */ }
Partition and Drain
let (evens, odds): (Vec<i32>, Vec<i32>) = v.into_iter().partition(|&x| x % 2 == 0);
Your Task
remove_duplicates(v: Vec<i32>) -> Vec<i32>— returns sorted vec with duplicates removed.flatten(vecs: Vec<Vec<i32>>) -> Vec<i32>— flattens a vec of vecs.two_pass_max(v: &[i32]) -> Option<i32>— returns the maximum element.partition_evens_odds(v: Vec<i32>) -> (Vec<i32>, Vec<i32>)— splits into (evens, odds).
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.