Sort based on multiple things in C++

the general pattern is:

bool CompareData(const T& a, const T& b) 
{ 
   if (a.PrimaryCondition < b.PrimaryCondition) return true;
   if (b.PrimaryCondition < a.PrimaryCondition) return false;

   // a=b for primary condition, go to secondary
   if (a.SecondaryCondition < b.SecondaryCondition) return true;
   if (b.SecondaryCondition < a.SecondaryCondition) return false;

   // ...

   return false;
} 

where < indicates the “less than” in the desired sort order, you might need to use custom comparison operators for that (e.g. strcmp for strings,or reverse the < if you want to order descending) (thanks Harry for pointing this out)

I’ve used < on all conditions, since that’s sometimes the only comparison operation available, e.g. when you have to use an unknown data type’s comparison predicate.

[edit] Note: the last line return false handles the case where aand bare considered equal for the comparator.

Imagine a.PrimaryCondition==b.PrimaryCondition and a.SecondaryCondition==b.SecondaryCondition – in this case, none of the previous conditions returns any value.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)