Reputation: 39
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.
Upvotes: 0
Views: 1043
Reputation: 6125
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 << ' ';
}
Upvotes: 4