macro_rules! sorted {
( $collection:expr ) => { ... };
( $collection:expr, $compare_fn:expr ) => { ... };
}Expand description
Creates a sorted Vec with cloned elements of the input collection, leaving the original
collection untouched.
The input collection should support .iter() method that returns an Iterator over its
elemnts.
There are two ways to invoke this macro:
- with one argument, a mutable collection
- uses
slice::sort_unstableto sort
- uses
- with two arguments, a mutable collection followed by a closure
- passes the closure to
slice::sort_unstable_byto sort
- passes the closure to
ยงExamples
#[macro_use] extern crate colmac;
use std::cmp::Ordering::{Equal, Greater, Less};
// sort without a custom closure
let v1 = vec![2, 4, -1];
let v1_sorted = sorted!(v1);
assert_eq!(vec![2, 4, -1], v1); // v1 is not modified
assert_eq!(vec![-1, 2, 4], v1_sorted);
// sort with; sort in reverse order
let v2 = vec![2, 4, -1];
let v2_sorted = sorted!(v2, |a, b| match a.cmp(b) {
Less => Greater,
Greater => Less,
Equal => Equal,
});
assert_eq!(vec![2, 4, -1], v2); // v2 is not modified
assert_eq!(vec![4, 2, -1], v2_sorted);