Sort array by first element in subarray C ++

I have an array of arrays, for example :) [[4, 204], [10, 39], [1, 500]]. I want to sort them by the first element of the subarray to become: [[1, 500], [4, 204], [10, 39]].

I could not find the answers to this question for C++.

How do I do this in C++?

the code:

int n;
int time;  
int timeTable[100][2];

if (inputFile.is_open()) {

    for (int i = 0; i < 100; i++) {
        inputFile >> n;
        timeTable[i][0] = n;
        inputFile >> time;
        timeTable[i][1] = time;
    }

}
-5
source share
1 answer

One way to sort a two-dimensional array is to not sort the array itself.

Instead, sort the array of indices pointing inside the array, and then use the sorted index to access the elements. This is much easier to do than manipulate a 2d array in sorting.

, ( ), 1 , .

:

#include <algorithm>
#include <iostream>

int main()
{
    int index[3] = {0,1,2};
    int timeTable[3][2] = {{4, 204}, {10, 39}, {1, 500}};
    std::sort(index, index + 3, [&](int n1, int n2){ return timeTable[n1][0] < timeTable[n2][0]; });
    for (int i = 0; i < 3; ++i)
       std::cout << "The index is " << index[i] << ".  The data at this index is  [" << 
                 timeTable[index[i]][0] << " " << timeTable[index[i]][1] << "]\n";
}

, , 0 n-1, n - . std::sort , , . , , .

, - , , , timeTable. , , , (, - 20 20 , ).

, timeTable, ( , , timeTable[index[i]][0] timeTable[i][0]).


1 "" , "" ", StackOverflow, " " .

+1

Source: https://habr.com/ru/post/1689974/


All Articles