c++ – Sorting C++ Structs

c++criteriaperformancesorting

  • I have a vector of custom Struct that needs to be sorted on different criteria each time
  • Implementing operator < will allow only one criteria
  • But I want to be able to specify sorting criteria each time I call C++ standard sort.

How to do that?

  • Please note it is better to be efficient in running time..

Thanks

Best Answer

You can define what comparison function to use in each run of the sort algorithm by using the third argument:

template <class RandomAccessIterator, class StrictWeakOrdering>
void sort(RandomAccessIterator first, RandomAccessIterator last,
          StrictWeakOrdering comp);

A simple example:

struct person {
   std::string name;
   int age;
};
bool sort_by_name( const person & lhs, const person & rhs )
{
   return lhs.name < rhs.name;
}
bool sort_by_age( const person & lhs, const person & rhs )
{
   return lhs.age < rhs.age;
}
int main() {
   std::vector<person> people;
   // fill in the vector
   std::sort( people.begin(), people.end(), sort_by_name );
   std::sort( people.begin(), people.end(), sort_by_age );
}
Related Question