In the STL, is there a default function that sorts a rectangular 2D array based on a specified column? For instance, if I have:
Array-Index studentID grades
0 5 90
1 6 8
How do I get a list of the students based on grades ranking (i.e. Sort the grades column)? This should be a fairly common task. It would be clumsy to manually program a new sorting algorithm just for something so simple.
Sorting (Mutil-dimensional arrays)
Moderator: Board moderators
I will sort it as follows:
Code: Select all
#include <stdlib.h>
int cmp(const void *a, const void *b)
{
int *x=(int *)a, *y=(int *)b;
return x[2]-y[2];
}
int main()
{
int array[100][3], n;
...
qsort(array, n, sizeof(int)*3, cmp);
...
return 0;
}
-
- A great helper
- Posts: 481
- Joined: Sun Jun 19, 2005 1:18 am
- Location: European Union (Slovak Republic)
Re: Sorting (Mutil-dimensional arrays)
To sort by the 3rd column you can like this:
Code: Select all
bool cmp3(const vector<int> &a, const vector<int> &b) {return a[3]<b[3];}
vector< vector<int> > V;
sort(V.begin(), V.end(), cmp3);