c++ - C++ 中各种自定义比较器函数之间的差异

标签 c++ sorting comparator

我发现有不同的方法可以为用户定义的对象定义自定义比较函数。我想知道在选择其中之一之前应该考虑哪些事项。

如果我有学生对象,我可以通过以下方式编写自定义比较函数。

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/

相关文章:

java - 想要使用比较器按时间戳对 ArrayList 中的聊天进行排序,但它不起作用,我不知道为什么

c++ - 窗口移动后点击坐标

C++ STL 容器。为每个不同的实例参数化一个比较器

c++ - 有符号/无符号不匹配和函数在转换为函数时不带 2 个参数

java - 如何从文本文件排序并写入另一个文本文件Java

java - 如何重现 "Comparison method violates its general contract"IllegalArgumentException

c++ - 为什么我的默认参数被忽略?

java - 排序数组并反射(reflect)另一个数组中的变化

R按因子或整数列出数据框中的前n个条目

Java SortedSet + Comparator,与equals()一致性问题