我发现有不同的方法可以为用户定义的对象定义自定义比较函数。我想知道在选择其中之一之前应该考虑哪些事项。
如果我有学生对象,我可以通过以下方式编写自定义比较函数。
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 进行排序,我可以使用以下方法之一。
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;
});
这些方法有何不同,我应该如何在这些方法之间做出选择。提前致谢。
最佳答案
不同方法之间的性能差异不大,但是使用<
将使您更加灵活,并使使用内置插件变得更加容易。我也认为使用 ()
有点奇怪。
您的示例中更大的问题是您的方法应该使用 const refs 而不是值。 IE。 bool operator<(Student ob)
可能是friend bool operator<(const Student& ls, const Student& rs){...}
。另请参阅here有关重载运算符时要考虑的不同事项的一些示例。
关于c++ - C++ 中各种自定义比较器函数之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422886/