Sorting (Mutil-dimensional arrays)

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
New poster
Posts: 12
Joined: Mon Oct 17, 2005 2:35 am
Location: Canada

Sorting (Mutil-dimensional arrays)

Post by bluebird » Thu Oct 20, 2005 5:33 am

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.

User avatar
A great helper
Posts: 274
Joined: Wed Oct 20, 2004 11:51 pm
Location: Hong Kong

Post by Cho » Thu Oct 20, 2005 6:17 am

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;

User avatar
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Re: Sorting (Mutil-dimensional arrays)

Post by Martin Macko » Sat Dec 10, 2005 1:23 pm

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);

Post Reply

Return to “C++”