CodeBlanks Logo Icon CodeBlanks

Summary - Vectors

Combine push, get and for to build a shopping cart.

Vectors summary

Vec<T> is a growable array living on the heap. Creating: Vec::new(), vec![..], vec![x; n], with_capacity. Changing: push, pop (Option), insert, remove, extend, clear. Reading: v[i] (panic risk) or get (Option). Looping: &v reads, &mut v modifies, v consumes.

Sorting and filtering

Useful methods that work in place:

let mut v = vec![5, 3, 8, 3, 1, 8];
v.sort();                  // [1, 3, 3, 5, 8, 8]
v.dedup();                 // [1, 3, 5, 8]
v.retain(|&x| x > 2);      // [3, 5, 8]
v.reverse();               // [8, 5, 3]

Floating-point numbers can't be sorted with sort (because of NaN); v.sort_by(|a, b| a.total_cmp(b)) is used.

Practice Clean and filter

For let mut v = vec![5, 3, 8, 3, 1, 8];, apply sort, dedup and retain(|&x| x > 2) in order; print the result with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let mut v = vec![5, 3, 8, 3, 1, 8];
    v.sort();
    v.dedup();
    v.retain(|&x| x > 2);
    println!("{:?}", v);
}

Expected output

[3, 5, 8]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is <code>v</code> after <code>let mut v = vec![3, 1, 3, 2]; v.sort(); v.dedup();</code>?

  • [1, 3, 2]
  • [1, 2, 3] Correct answer
  • [1, 2, 3, 3]
  • [3, 1, 2]

Explanation: dedup only removes consecutive duplicates, which is why sort is needed first.

2 Keep by condition

Question
let mut v = vec![1, 3, 5, 8];
v.____(|&x| x > 2);   // [3, 5, 8]
Answer
let mut v = vec![1, 3, 5, 8];
v.retain(|&x| x > 2);   // [3, 5, 8]

Explanation: retain keeps the elements that satisfy the condition, in place.

3 Method and effect

Term Meaning
sort() Ascending
dedup() Removes consecutive duplicates
retain(..) Keeps matching ones
reverse() Reverses the order

All lessons in Beginner