Maison > Article > développement back-end > Comment puis-je trier efficacement un tableau de sous-tableaux en fonction de leur premier élément ?
Sorting arrays based on the first element of their subarrays poses a challenge. Rather than manipulating the array directly, consider an alternative approach.
Create an array of indices that refer to the original array. Sort the indices based on the first element of the subarrays at those indices.
This strategy has several advantages:
Here's an example in C++:
#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, [&timeTable](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"; } return 0; }
Live Example
By using indices instead of manipulating the original array, you can sort complex data structures more efficiently and conveniently.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!