I want to sort a vector (inplace) by a predefined ordering in Rust.
For example
let i = vec![0, 3, 2, 1];
let mut v = vec!["a", "b", "c", "d"];
v.sort_by_index(&i);
assert_eq!(v, &["a", "d", "c", "b"]);
I would like to do this inplace. In my use case, v
takes up a lot of memory.
Note: this question is a natural follow-on from How to get the indices that would sort a vector in Rust?
CodePudding user response:
In the same way it enough to implement yourself
let i = vec![0, 3, 2, 1];
let mut v = vec!["a", "b", "c", "d"];
v = i.into_iter().map(|x| v[x]).collect::<Vec<&str>>();
assert_eq!(v, &["a", "d", "c", "b"]);
CodePudding user response:
You can create a HashMap
or BTreeMap
lookup table and use it as key searcher:
use std::collections::HashMap;
fn main() {
let i = vec![0, 3, 2, 1];
let mut v = vec!["a", "b", "c", "d"];
let keys: HashMap<_, _> = v.iter().cloned().zip(i.iter()).collect();
v.sort_by_cached_key(|e| keys[e]);
assert_eq!(v, &["a", "d", "c", "b"]);
}