Sub topic 5
Common Vec methods: insert, remove, sort, dedup, retain
This chapter assumes you can create a Vec, push to it, and read from it with indexing or get. It also assumes you know & and &mut borrowing and how closures are written. The methods here change a Vec in place, so each one needs a mut binding. Each has a cost and a failure mode worth knowing before you use it.
The working model
A Vec<T> stores its elements in one contiguous block of memory. Two things follow from that:
- Putting an element in the middle means moving every element after it one slot right. Taking one out means moving them left.
- Methods that reorder or filter work on the existing buffer. They do not build a new
Vec.
| Method | What it does | Cost |
|---|---|---|
| `insert(i, x)` | Puts `x` at index `i`, shifting later elements right | O(n) |
| `remove(i)` | Removes and returns the element at `i`, shifting later elements left | O(n) |
| `swap_remove(i)` | Removes and returns the element at `i`, filling the gap with the last element | O(1) |
| `sort()` and variants | Reorders the elements | O(n log n) |
| `dedup()` | Removes consecutive duplicates | O(n) |
| `retain(f)` | Keeps only elements for which `f` returns true | O(n) |
| `truncate(n)`, `clear()` | Shortens the `Vec` | O(1) for types without a destructor, otherwise each dropped element is visited |
| `drain(range)` | Removes a range and yields it as an iterator | O(n) |
The next diagram shows how to pick a removal method.
insert and remove
The five methods from the chapter title work together in one short program.
fn main() {
let mut v = vec![5, 3, 8, 3, 1];
v.sort(); // [1, 3, 3, 5, 8]
v.dedup(); // [1, 3, 5, 8]
v.retain(|&x| x > 1); // [3, 5, 8]
v.insert(0, 2); // [2, 3, 5, 8]
let removed = v.remove(1); // removes 3
println!("{removed} {:?}", v); // 3 [2, 5, 8]
}insert(index, value) accepts any index from 0 up to and including len(). An index equal to len() appends. remove(index) returns the removed value, so you can use it or drop it.
If you do not care about order, swap_remove avoids the shift:
fn main() {
let mut v = vec![1, 2, 3];
v.insert(3, 4); // index == len() appends
println!("{:?}", v); // [1, 2, 3, 4]
let removed = v.swap_remove(0); // the last element moves into slot 0
println!("{removed} {:?}", v); // 1 [4, 2, 3]
}In a hot loop, repeated remove(0) on a large Vec is quadratic overall. If you need to remove from the front often, look at VecDeque, or use swap_remove when order is irrelevant.
sort and its variants
sort() requires T: Ord. It is stable, which means equal elements keep their original relative order. sort_unstable() does not promise that, but it is usually faster and does not allocate scratch memory. Choose it when equal elements are indistinguishable, such as plain integers.
Floating-point numbers are the common stumbling block. f64 implements PartialOrd but not Ord, because NaN is not comparable. temps.sort() on a Vec<f64> does not compile. Use sort_by instead:
fn main() {
let mut temps: Vec<f64> = vec![21.5, 18.0, 25.25, 19.75];
temps.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{:?}", temps); // [18.0, 19.75, 21.5, 25.25]
temps.sort_by(|a, b| b.total_cmp(a)); // descending, never panics
println!("{:?}", temps); // [25.25, 21.5, 19.75, 18.0]
}partial_cmp(...).unwrap() panics if the data contains NaN. total_cmp defines a complete order over all floats, so it never panics.
To sort structs by a field, use sort_by_key. Wrap the key in std::cmp::Reverse for descending order:
use std::cmp::Reverse;
#[derive(Debug)]
struct Player {
name: String,
score: u32,
}
fn main() {
let mut players = vec![
Player { name: "Ana".to_string(), score: 70 },
Player { name: "Bo".to_string(), score: 90 },
Player { name: "Cy".to_string(), score: 70 },
];
players.sort_by_key(|p| Reverse(p.score));
for p in &players {
println!("{} {}", p.name, p.score);
}
// Bo 90
// Ana 70
// Cy 70
}Ana stays ahead of Cy because the sort is stable.
dedup only removes neighbors
dedup() removes consecutive equal elements. It does not search the whole Vec. Duplicates that are separated by another value survive:
fn main() {
let mut v = vec![1, 1, 2, 1, 1, 3, 3];
v.dedup();
println!("{:?}", v); // [1, 2, 1, 3]
let mut w = vec![1, 1, 2, 1, 1, 3, 3];
w.sort();
w.dedup();
println!("{:?}", w); // [1, 2, 3]
}The usual way to remove every duplicate is therefore sort() followed by dedup(). This changes the order. If you need to keep first-seen order, track seen values in a HashSet and use retain (see the last section).
dedup_by_key compares a derived key, and it keeps the first element of each run:
fn main() {
let mut words = vec!["Apple", "apple", "Bob", "bob", "bob"];
words.dedup_by_key(|w| w.to_lowercase());
println!("{:?}", words); // ["Apple", "Bob"]
}dedup_by takes a closure that receives two elements and decides whether they count as equal.
retain
retain takes a closure that receives &T. It keeps the elements for which the closure returns true:
fn main() {
let mut nums: Vec<i32> = (1..=10).collect();
nums.retain(|&x| x % 2 == 0);
println!("{:?}", nums); // [2, 4, 6, 8, 10]
let mut names = vec![String::from("ann"), String::new(), String::from("bo")];
names.retain(|s| !s.is_empty());
println!("{:?}", names); // ["ann", "bo"]
}The pattern |&x| destructures the reference, which works because i32 is Copy. For String, the closure receives &String and you call methods on it directly.
retain is the right tool when you would otherwise loop over indexes and call remove. Removing inside a for x in &v loop does not compile, because the loop holds a shared borrow of the Vec. Removing inside an index loop compiles but skips elements, because everything shifts left after each removal. retain avoids both problems and does the work in one pass.
retain_mut is the same, but the closure receives &mut T. You can modify an element and decide whether to keep it in one step.
Other in-place methods worth knowing
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
let middle: Vec<i32> = v.drain(1..3).collect(); // removes indexes 1 and 2
println!("{:?} {:?}", middle, v); // [2, 3] [1, 4, 5, 6]
v.truncate(2); // keep the first two
v.extend([9, 9]); // append from any iterable
println!("{:?}", v); // [1, 4, 9, 9]
v.reverse();
println!("{:?}", v); // [9, 9, 4, 1]
v.clear();
println!("{} {}", v.len(), v.is_empty()); // 0 true
}drain removes the range even if you never consume the iterator it returns. truncate and clear change len but keep the allocated capacity, which the capacity chapter covers.
Keeping first-seen order while removing duplicates
Combining retain with a HashSet gives an order-preserving dedup:
use std::collections::HashSet;
fn main() {
let mut v = vec![3, 1, 3, 2, 1, 4];
let mut seen = HashSet::new();
v.retain(|x| seen.insert(*x)); // insert returns false if already present
println!("{:?}", v); // [3, 1, 2, 4]
}retain visits elements in order and calls the closure once per element. That is why a closure with side effects, like this one, is reliable.
Common errors
- Calling
dedupon unsorted data and expecting global uniqueness. - Calling
sort()onVec<f64>. Usesort_bywithtotal_cmp. - Passing an out-of-range index to
insertorremoveand getting a panic. - Forgetting
muton the binding, which gives "cannot borrow as mutable". - Assuming
sort_unstablekeeps equal elements in order. It does not. - Holding a reference like
let first = &v[0];and then calling one of these methods. The borrow checker rejects it because all of them need&mut self.
Exercise
You have let mut v = vec![4, 1, 4, 2, 1, 3];. Write the code that leaves v containing each value once, in ascending order, and then removes every value below 2. What does v contain at the end?
Show answer
Call v.sort(); to get [1, 1, 2, 3, 4, 4], then v.dedup(); to get [1, 2, 3, 4], then v.retain(|&x| x >= 2);. The final value is [2, 3, 4]. sort must come before dedup because dedup removes only consecutive duplicates.
Exercise
Why does for i in 0..v.len() { if v[i] % 2 == 0 { v.remove(i); } } give wrong results or a panic, and what replaces it?
Show answer
Each remove shifts later elements left, so the loop skips the element that moved into index i. The range 0..v.len() was also computed before any removal, so i can reach an index that no longer exists, and v[i] then panics. Replace the loop with v.retain(|&x| x % 2 != 0);, which makes one pass and keeps the odd values.