如何在类(C )中作为参数传递函数
How to pass a function as parameter in class(C++)
我在做一个学生的清单:1.via名称2.via出生日期两者都只有不同的比较类型,其余的是相同的。因为我不希望使用模板类型来执行此操作:
class Student
{
Date date; // Date is a class
Name name; // Name is a class
public:
Date getDate() { return date; }
Name getName() { return name; }
};
class ListOfStudent
{
vector<Student> List;
public:
bool CompareDate(Date &d1, Date &d2); // define d1<d2
bool CompareName(Name &n1, Name &n2); // define n1<n2
void SortViaName()
{
for (int i = 0; i < List.size(); ++i)
int min = i;
for (int j = i + 1; j < List.size(); ++j)
{
if (CompareName(List[j].getName(), List[min].getName()))
min = j;
}
if (min != i)
swap(List[i], List[min]);
}
void SortViaDate()
{
for (int i = 0; i < List.size(); ++i)
int min = i;
for (int j = i + 1; j < List.size(); ++j)
{
if (CompareName(List[j].getDate(), List[min].getDate()))
min = j;
}
if (min != i)
swap(List[i], List[min]);
}
// Because i do not want to duplicate code so I do:
template <typename T>
void Sort(bool (*f)(T, T), T (*t)())
{
for (int i = 0; i < List.size(); ++i)
int min = i;
for (int j = i + 1; j < List.size(); ++j)
{
if ((*f)(DS[j].(*t)(), List[i].(*t)()))
min = j;
}
if (min != i)
swap(List[i], List[min]);
}
};
它在模板功能上有问题,所以我需要您的支持。
为了使事情变得通用,设置内容的最简单方法是使CompareThing
函数可选地使用Student&
,而不是Date
或Name
。
注意: CompareDate
和 CompareName
应该是 static或global ,这样您就可以将它们作为功能指针传递。
// We'll keep these
// Also they should either be static or global
bool CompareDate(Date &d1,Date &d2); //define d1<d2
bool CompareName(Name &n1,Name &n2); //define n1<n2
// Because these can both be used with Student, it's easy to template over them
bool CompareDate(Student &s1, Student &s2) {
return CompareDate(s1.getDate(), s2.getDate());
}
bool CompareName(Student &s1, Student &s2) {
return CompareName(s1.getName(), s2.getName());
}
然后,我们可以像这样写Sort
:
void Sort(bool(*compare)(Student&, Student&)) {
std::sort(List.begin(), List.end(), compare);
}
void SortViaName() {
Sort(CompareName);
}
void SortViaDate() {
Sort(CompareDate);
}
使用您的选择排序
我们可以编写Sort
将功能作为参数,然后使用您的选择排序而不是std::sort
:
void Sort(bool (*compare)(Student&, Student&))
{
for (int i = 0; i < List.size(); ++i) {
int min = i;
for (int j = i + 1; j < List.size(); ++j)
{
if (compare(List[j].getName(), List[min].getName()))
min = j;
}
if (min != i)
swap(List[i], List[min]);
}
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数