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
  • 18,008
  • 2
  • 24
  • 52
rKA
  • 3
  • 2
  • 1
    you should take a look at how `std::sort` does it – 463035818_is_not_an_ai Mar 22 '21 at 13:37
  • 2
    Use `std::sort` with `std::vector`: Does this answer your question? [Sorting a vector of custom objects](https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects) – scohe001 Mar 22 '21 at 13:39
  • `temp=a[j]; a[j]=a[j+1]; a[j+1] = temp;` -- All of that could simply be: `std::swap(a[j], a[j+1]);` – PaulMcKenzie Mar 22 '21 at 13:46
  • A bubble sort? You might want to learn some more efficient sorting algorithm, or simply use the one from a standard library.... – CiaPan Mar 22 '21 at 23:18

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_an_ai
  • 109,796
  • 11
  • 89
  • 185