乐闻世界logo
搜索文章和话题

How to sort a vector in Rust?

1个答案

1

In Rust, a vector is a collection for storing elements of the same type, and it can be easily sorted using methods from the standard library. Rust provides multiple sorting methods, and here I will introduce two commonly used ones: sort() and sort_by().

1. Using sort()

The sort() method is the simplest way to sort, applicable when the element type implements the Ord trait. This method sorts the elements in the vector in ascending order. For example:

rust
fn main() { let mut vec = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; vec.sort(); println!("{:?}", vec); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9] }

This code creates a vector of integers and sorts it using the sort() method.

2. Using sort_by()

When you need to customize the sorting criteria, the sort_by() method is a suitable choice. You can pass a closure to determine the sorting order. For example, if we want to sort by the absolute value of numbers:

rust
fn main() { let mut vec = vec![-5, 2, -3, 1, 6, -1]; vec.sort_by(|a, b| a.abs().cmp(&b.abs())); println!("{:?}", vec); // Output: [1, -1, 2, -3, -5, 6] }

Here, sort_by() accepts a closure that compares the absolute values of pairs of elements and sorts based on the comparison result.

Summary

Using sort() or sort_by() to sort vectors in Rust is intuitive and powerful. With a simple sort(), you can quickly sort types that implement Ord, while sort_by() offers high customizability for more complex sorting requirements. In actual development, choosing the appropriate method can effectively improve code readability and performance.

2024年8月7日 17:04 回复

你的答案