I have two Vec
s that correspond to a list of feature vectors and their corresponding class labels, and I'd like to co-sort them by the class labels.
However, Rust's sort_by
operates on a slice rather than being a generic function over a trait (or similar), and the closure only gets the elements to be compared rather than the indices so I can sneakily hack the sort to be parallel.
I've considered the solution:
let mut both = data.iter().zip(labels.iter()).collect();
both.sort_by( blah blah );
// Now split them back into two vectors
I'd prefer not to allocate a whole new vector to do this every time because the size of the data can be extremely large.
I can always implement my own sort, of course, but if there's a builtin way to do this it would be much better.
u32
, so 4 bytes per elem) and sort that viasort_by
indexing intolabels
. The result can then be used to permutedata
andlabels
into the right order. (Unfortunately still allocates O(n) memory, of course.)sort_by
doesn’t do it itself, you’d need to implement the sorting yourself, probably usingsort_by
as the basis. Oh, and it can’t just give you the indices, because they’re not constant. If you really were to insist on usingsort_by
, you’d need to do pointer comparison to get the index of an element in the slice and then figure out whatsort_by
is going to do with your response and do it to the other vector yourself, which would be an utterly mad and fragile way of doing it. So yeah, just look at whatsort_by
does and copy it.sort_by
already allocates 2n space, so you're not going to avoid allocation unless you use a different sorting function.[T]::sort/sort_by
is a stable sort. There are alternatives on crates.io if you need a non-stable nonallocating sort.