What is a best way to sort a vector?


#1

I woud like to sort a vector. The only way I see would be to use the sort_by for slices. I thought I would have had to convert to slice, sort, and convert back to vector, but no. I have the following, but I am not completely sure I understand it.

let mut v = DVector::<f64>::new_random(4);
v.as_mut_slice().sort_by(|a, b| a.partial_cmp(b).unwrap_or(Equal));

I sort of expected that pub fn as_mut_slice(&mut self) -> &mut [N] would make a copy of my vector and five me a reference to that copy, but it’s is actually directly referring to the representation of the vector. Should I have known better by just reading the signature? That & in &mut [N] is a hint, but was my first idea technically possible? Does that & in the return type always indicate reference to the input value, or can it also be reference to some new value that is made within the function? (I say technically, 'cause now that I’ve reflected on it a bit, I guess it’s the very point of slices to give reference to what’s in the structure…)


#2

The approach you used for sorting is the right one :slight_smile:

It is impossible for a structure to copy itself and return a reference to the copy because the copy would be invalid as soon as the method returns. For example the following cannot compile:

fn copy_and_return_ref(&mut self) -> &mut Self {
    let clone = self.clone();
    &mut clone // impossible because `clone` will be dropped when the method returns, thus invalidating the pointer.
}

So it is generally true that a method with this kind of signature only returns a reference to some of its internal data. This data can be created by the method itself though. A method like the following is perfectly legal for a collection because the added data remains valid after the method returns:

struct MyVec {
  v: Vec<f32>
}

impl MyVec {
    fn push_zero(&mut self) -> &mut f32 {
        self.v.push(0.0);
        let len = self.len();
        &mut self.v[len - 1]
    }
}