0

My question is how the compare function in the C++ sort function takes parameters. if I want to sort an array but also want to preserve the index of the elements i thought of sorting the index array based on the elements in the actual array. The issue is i am not able to find how to pass the parameters to the compare function. suppose the array is 3 5 4 2 indexes are 0 1 2 3 . I want the index array output 3 0 2 1 which is 2 3 4 5 . how can i do that using the sort function.

1 Answers1

4

One way to do it :

vector<int> data{  3, 5, 4, 2 },
            index{ 0, 1, 2, 3 };
sort(index.begin(), index.end(), [&data](int i, int j) { return data[i] < data[j]; });
for (int i : index)
{
    cout << i << ' ';
}
Sid S
  • 6,037
  • 2
  • 18
  • 24
  • 1
    In case you don't know what he's doing [&data](int i, int j) is a lambda function, you can think of it like 1 instance of a simple inline. – Jon Doe Nov 02 '19 at 01:43
  • If a lambda compare wasn't available, then a vector of pointers could be used, `vectorptr{&data[0], &data[1], &data[2], &data[3]};`. The compare function input would be two `int *`. To convert ptr to index: `index[i] = ptr[i] - &data[0];` . – rcgldr Nov 02 '19 at 07:53