所以,我基本上学习了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[aj].name替换为r[aj].roll和r[aj].total。这有可能吗?
发布于 2021-03-22 21:41:17
您可以将函数作为比较器传递给函数:
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如何让您传递一个自定义比较器并执行类似的操作。
https://stackoverflow.com/questions/66747158
复制相似问题