Sorting multidimensional array and keeping index C ++
Is it possible to sort a multidimensional array (line by line) using sorting in C ++ so that I can store 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 index will be:
{2,0,1,3} {0,3,2,1} {1,3,0,2} { 1,0,2,3}
source to share
First, create an array of integer indices; here it is for a 1D array:
int ind[arr.size()];
for( int i=0; i<arr.size(); ++i)
ind[i] = i;
Then create a comparison object. Here's a rough example of this in C ++ 99 lingo; for C ++ 11, you can shorten this using lambda:
struct compare
{
bool operator()( int left, int right ) {
return arr[left] < arr[right];
}
};
Sorting an array of indices using this functor:
std::sort( ind, ind+sizeof(arr), compare );
Finally, use a sorted index array to order the array of values.
source to share
Yes. To sort line by line, you must set the appropriate start and end points in the function sort
. To keep the index part, you can first create pairs of array and index elements using the command make_pair
. After executing the above code, you can restore the index array.
You will need to do something like this (I haven't tried it yet):
for (i = 0; i < matrix.size(); i++)
{
sort(matrix[i].begin(), matrix[i].end());
}
Remember to add the index as the second element in a pair, because by default the pair comparison operator checks the first element followed by the second element.
source to share