Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a vector in Rust?

Tags:

rust

What is the currently recommended method for sorting values in a vector?

like image 832
Maxim Sloyko Avatar asked Nov 10 '14 03:11

Maxim Sloyko


People also ask

How do you sort in Rust?

There are two ways of sorting in Rust: sort_by() function and sort() function. The sort_by() function sorts the vector according to the given key, an integer or string, while the sort() function sorts the vector according to its element's order.

Can you sort vectors?

A vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.

How do you sort an object in vector?

You can sort a vector of custom objects using the C++ STL function std::sort. The sort function has an overloaded form that takes as arguments first, last, comparator. The first and last are iterators to first and last elements of the container.

Can you sort a vector string?

Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contains single numeric character for example, { '1', ' '} but to sort numeric vector of string with multiple character for example, {'12', '56', '14' } one should write own comparator inside sort() function.


2 Answers

A mutable slice of elements with a total ordering has a sort method.

Because Vec<T> implements DerefMut<[T]>, you can call this method directly on a vector, so vector.sort() works.

like image 168
Chris Morgan Avatar answered Sep 20 '22 20:09

Chris Morgan


To sort a vector v, in most cases v.sort() will be what you need.

If you want to apply a custom ordering rule, you can do that via v.sort_by(). That includes cases where you want to sort values that:

  • don't implement Ord (such as f64, most structs, etc);
  • do implement Ord, but you want to apply a specific non-standard ordering rule.

Also note that sort() and sort_by() use a stable sorting algorithm (i.e., equal elements are not reordered). If you don't need a stable sort, you can use sort_unstable() / sort_unstable_by(), as those are generally a bit faster and use less memory.

like image 24
at54321 Avatar answered Sep 20 '22 20:09

at54321