【发布时间】:2016-07-17 15:31:58
【问题描述】:
我发现有多种方法可以为用户定义的对象定义自定义比较函数。我想知道在选择一个而不是另一个之前应该考虑的事情。
如果我有学生对象,我可以通过以下方式编写自定义比较函数。
struct Student
{
string name;
uint32_t age;
// Method 1: Using operator <
bool operator<(const Student& ob)
{
return age < ob.age;
}
};
// Method 2: Custom Compare Function
bool compStudent(const Student& a, const Student& b)
{
return a.age < b.age;
}
// Method 3: Using operator ()
struct MyStudComp
{
bool operator() (const Student& a, const Student& b)
{
return a.age < b.age;
}
}obComp;
要对一组学生进行排序,我可以使用以下任一方法。
vector<Student> studs; // Consider I have this object populated
std::sort(studs.begin(), studs.end()); // Method 1
std::sort(studs.begin(), studs.end(), compStudent); // Method 2
std::sort(studs.begin(), studs.end(), obComp); // Method 3
// Method 4: Using Lambda
sort(studs.begin(), studs.end(),
[](const Student& a, const Student& b) -> bool
{
return a.age < b.age;
});
这些方法有什么不同,我应该如何在它们之间做出决定。提前致谢。
【问题讨论】:
-
别忘了 lambda。
-
本身确实没有“正确”的方式,但如果您的对象有自定义比较器(即
operator<等)有意义,那么简单地使用这些比较器是明智的。但是,您可能希望根据不同的字段成员对对象进行排序,因此在这种情况下,基于这些字段比较提供自定义 lambda 是有意义的。
标签: c++ sorting comparator