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.
Asked
Active
Viewed 984 times
0
-
1The comparator passed to `std::sort` doesn't have to be a function - it can also be an object of a class with overloaded `operator()`. This object can maintain state. A lambda expression is a common way to manufacture this object. – Igor Tandetnik Nov 02 '19 at 00:44
-
See also https://stackoverflow.com/a/12399290/10990718 – dms Nov 02 '19 at 00:45
-
thanks a lot for the link. This solved my issue. – Dheeraj Ramchandani Nov 02 '19 at 12:55
1 Answers
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
-
1In 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, `vector
ptr{&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