Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort multidimensional array and keep index C++

Is it possible to sort a multidimensional array (row by row) using sort in C++ such that I can keep the index?

For example,

13, 14, 5, 16
0, 4, 3, 2
7, 3, 7, 6
9, 1, 11, 12

Becomes:

{ 5,13,14,16}
{ 0,2,3,4 }
{ 3,6,7,7}
{ 1,9,11,12 } 

And the array with the index would be:

{2,0,1,3}
{0,3,2,1}
{1,3,0,2}
{ 1,0,2,3}
like image 724
Eli Avatar asked Jul 20 '26 11:07

Eli


1 Answers

First create the array of integer indices; here it is for 1D array:

int ind[arr.size()];
for( int i=0; i<arr.size(); ++i)
    ind[i] = i;

Then create the comparison object. Here is a ballpark of that in C++99 lingo; for C++11 you can shortcut that by using a lambda:

struct compare
{
    bool operator()( int left, int right ) {
        return arr[left] < arr[right];
    }
};

The sort the index array using that functor:

std::sort( ind, ind+sizeof(arr), compare );

Finally, use the sorted index array to order the values array.

like image 61
Michael Avatar answered Jul 22 '26 02:07

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!