提问者:小点点

C++类中不同数据成员的排序


所以,我基本上学会了C++中的类和模板函数。假设我有一个班级学生的记录,上面有他们的卷号、姓名和总分。我正在使用索引排序对记录进行排序。现在可以根据姓名、卷面或总分进行排序。如何使用模板函数合并所有这三个?

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;
      }
    }
  }
}

所以我不想一遍又一遍地写函数,而是想用R[A[j]].name替换R[A[j]].roll和R[A[j]].total。有可能吗?


共1个答案

匿名用户

可以将函数作为比较器传递给函数:

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)
    /*...*/ 
}

然后可以使用自定义谓词调用它,例如比较name成员:

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

除非这是一个关于编写自己的排序例程的练习,否则应该使用std::sort。即使这样,您也可以查看std::sort如何允许您传递自定义比较器,并执行类似的操作。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|类|中|数据|成员|排序)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?