Day 13j: Using Vectors with Rust’s std Algorithms
Introduction
Rust’s standard library provides a number of useful algorithms that can be applied to vectors. In this session, we’ll explore some key algorithms like retain()
and operations for merging and partitioning vectors.
Using retain()
to Filter Elements
The retain()
method allows you to filter elements in a vector by retaining only those that satisfy a given condition.
fn main() {
let mut numbers = vec![1, 2, 3, 4, 5, 6];
numbers.retain(|&x| x % 2 == 0);
println!("{:?}", numbers); // Output: [2, 4, 6]
}
Partitioning a Vector
You can use the partition()
method to split a vector into two parts based on a condition.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let (evens, odds): (Vec<i32>, Vec<i32>) = numbers.into_iter().partition(|&x| x % 2 == 0);
println!("Evens: {:?}", evens); // Output: [2, 4, 6]
println!("Odds: {:?}", odds); // Output: [1, 3, 5]
}
Conclusion
Rust’s standard library provides several algorithms that allow you to filter, partition, and manipulate vectors efficiently. Learning how to apply these algorithms can significantly improve the readability and performance of your code.