struct mycompare和static bool mycompare有什么区别?

What's the difference between struct mycompare and static bool mycompare?

本文关键字:mycompare 什么 区别 bool static struct      更新时间:2023-10-16
struct mycompare1 {
    bool operator() (const Interval a, const Interval b) {
        return a.start < b.start;
    }
} mycompare1_instance;
static bool mycompare2(const Interval a, const Interval b) {
    return a.start < b.start;
}

Q1:这两者有什么区别。似乎mycompare1_instance以某种方式等于这样的mycompare2。以下两行似乎做同样的事情。

sort(intervals.begin(), intervals.end(), mycompare1);
sort(intervals.begin(), intervals.end(), mycompare2);

谁能解释一下?

Q2:"静态"在这里有什么用?

谢谢你!

第一种情况定义了 operator(),因此您可以将其用作函数 - 简而言之,它们是函子。优点是它可以有一个状态,并且根据您定义 operator() 的方式,您可以将该类的实例用作函数。第二种情况只是一个静态函数,不保存类/结构意义上的状态。

我怀疑这个问题与函子有关

即你见过的

mycompare_instance1(x,y)

mycompare2(x,y)

第一个是函子。它用于我们需要制作既是具有状态的对象,又可以像函数一样调用的东西。第二个是简单的函数