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?
You can pass a functor as comparator to the function:
Then you can call it with custom predicates, eg to compare
namemember:Unless this is an exercise about writing your own sorting routine, you should use
std::sort. Even then you can look at howstd::sortlets you pass a custom comparator and do similar.