How to sort a vector of indices based on the indexed values in another vector?

Viewed 312

I have a struct of the shape

pub struct ExampleData {
    data: Vec<u32>,
    data_ids: Vec<u32>,
}

Sample data

{data: [9,8,7], data_ids: [0,1,2]}

I want to sort the data_ids vector based on the values of the data vector and I have implemented the following method:

impl ExampleData {
    pub fn sorting(&mut self) {
        self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
    }
}

The above code does not work:

error[E0277]: the type `[u32]` cannot be indexed by `&u32`
  --> src/lib.rs:10:38
   |
10 |         self.data_ids.sort_by(|a, b| self.data[a].cmp(self.data[b]));
   |                                      ^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `SliceIndex<[u32]>` is not implemented for `&u32`
   = note: required because of the requirements on the impl of `Index<&u32>` for `Vec<u32>`

What am I doing wrong here?

0 Answers
Related