Sorting array of classes

Hello. I used this ( http://www.cplusplus.com/forum/general/97555/#msg523529 ) example to sort an array of classes. But what if I want to modify "Option 1" (made by Stewbond) so that if lhs.num1==rhs.num1 the program would remain sorting by another member (num2 in this example)?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <algorithm>
#include <tuple>
struct a
{
    int num1;
    int num2;
};

bool acompare(a lhs, a rhs) 
{ 
    return std::tie(lhs.num1, lhs.num2) < std::tie(rhs.num1, rhs.num2);
}

int main()
{
   a array[1000];
   std::sort(array, array+1000, acompare);
}
Thank you. This seems to work. Could you explain me how?
std::tie returns a tuple of references. And tuples already have well-defined comparison behavior: it compares first elements, if they equal, it compares seconds and so on.
Topic archived. No new replies allowed.