Using vector is much simpler, but assuming you can't use std::vector
, here is an alternate way of "sorting", based on the answer given here:
#include <iostream>
#include <algorithm>
int main()
{
int exampleArray[5][2] = {
{4, 20},
{1, 4},
{7, 15},
{8, 8},
{8, 1}
};
// create the indexing (there are 5 2D entries)
int index[] = {0,1,2,3,4};
// sort the index based on the second value in the 2D array
std::sort(index, index + 5, [&](int n1, int n2)
{ return exampleArray[n1][1] < exampleArray[n2][1]; });
// output results
for (int i = 0; i < 5; ++i)
std::cout << exampleArray[index[i]][0] << " " << exampleArray[index[i]][1] << "\n";
}
Output:
8 1
1 4
8 8
7 15
4 20
Basically, you want to sort the index array based on the second value in the 2D array. That's what the lambda function is stating -- the index array is being "sorted", and not the original 2D array.
Once the sorting is finished, the index array is used to access the items in the 2D array in a sorted fashion.
From there, if you want the changes stored in the actual 2D array, you could rebuild the original array using the sorted index:
// rebuild the original array using the sorted index
int tempArray[5][2] = {};
for (int i = 0; i < 5; ++i)
{
tempArray[i][0] = exampleArray[index[i]][0];
tempArray[i][1] = exampleArray[index[i]][1];
}
// copy the new sorted array to the original array
memcpy(exampleArray, tempArray, sizeof(exampleArray));