简体   繁体   English

按 class C++ 的不同数据成员排序

[英]Sorting by different data members of a class C++

So, I basically learnt class and also Template functions in C++.所以,我基本上学习了 class 以及 C++ 中的模板函数。 Suppose I have a record of students in a class with their roll number, name and total marks.假设我有一个 class 学生的记录,包括他们的卷号、姓名和总分。 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.因此,我不想一次又一次地编写函数,而是想用 r[a[j]].roll 和 r[a[j]].total 替换 r[a[j]].name。 Is that possible?那可能吗?

You can pass a functor as comparator to the function:您可以将仿函数作为比较器传递给 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:然后您可以使用自定义谓词调用它,例如比较name成员:

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 .除非这是关于编写自己的排序例程的练习,否则应该使用std::sort Even then you can look at how std::sort lets you pass a custom comparator and do similar.即使这样,您也可以查看std::sort如何让您传递自定义比较器并执行类似操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM