0

So, I basically learnt class and also Template functions in C++. Suppose I have a record of students in a class with their roll number, name and total marks. I am using index sorting to sort the records. Now the sorting can be done on the basis of name, roll or total marks. How to incorporate all three using template functions?

class record{
  public:
  int roll;
  string name;
  int total;
};
void sort_name(int a[], record r[],int n)
{
  int temp;
  bool xchange = true;
  for(int pass=1;pass<n&&xchange==true;pass++)
  {
    for(int j=0;j<n-pass;j++)
    {
      if(r[a[j]].name>r[a[j+1]].name)
      {
        temp=a[j];
        a[j]=a[j+1];
        a[j+1] = temp;
      }
    }
  }
}

So instead of writing the functions again and again I want to replace r[a[j]].name by r[a[j]].roll and r[a[j]].total. Is that possible?

Yksisarvinen
  • 13,037
  • 1
  • 18
  • 42
rKA
  • 3
  • 1

1 Answers1

2

You can pass a functor as comparator to the function:

template <typename Comparator>
void my_sort(int a[], record r[],int n, Comparator comp)
{
    /*...*/ 
    if (comp(r[a[j], r[a[j+1]]) // instead of   if(r[a[j]].name>r[a[j+1]].name)
    /*...*/ 
}

Then you can call it with custom predicates, eg to compare name member:

my_sort(a,r,n,[](const record& a, const record& b) { return a.name < b.name; });

Unless this is an exercise about writing your own sorting routine, you should use std::sort. Even then you can look at how std::sort lets you pass a custom comparator and do similar.

463035818_is_not_a_number
  • 64,173
  • 8
  • 58
  • 126