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: What is the difference between these two. It seems that mycompare1_instance somehow equals to mycompare2 like this. The following two lines seem to do the same thing.
Q1:这两者之间有什么区别。似乎mycompare1_instance在某种程度上等于mycompare2就像这样。以下两行似乎也做同样的事情。
sort(intervals.begin(), intervals.end(), mycompare1);
sort(intervals.begin(), intervals.end(), mycompare2);
Could anyone explain it?
谁能解释一下呢?
Q2: How is "static" useful here?
Q2:这里的“静态”有用吗?
Thx ahead!
先生!
2 个解决方案
#1
1
The first case defines operator() so you could could use it as a function - in short they are functors. The advantage is that it can have a state and depending how you define the operator() you could use the instance of that class as a function. Thse second case is simply a static functionn and does not hold the state in the sense of a class/struct.
第一种情况定义了operator(),因此您可以将它用作函数 - 简而言之它们是函子。优点是它可以具有状态,并且取决于您如何定义operator(),您可以将该类的实例用作函数。第二种情况只是一个静态函数,并不保持类/结构意义上的状态。
#2
0
I suspect the question is related to functors
我怀疑这个问题与仿函数有关
ie you have seen
即你见过
mycompare_instance1(x,y)
vs
VS
mycompare2(x,y)
The first one is a functor. It used where we need to make things that are both objects with state and can be invoked like functions. The second one is a simple function
第一个是仿函数。它用于我们需要制作既是状态对象又可以像函数一样调用的东西。第二个是一个简单的功能
#1
1
The first case defines operator() so you could could use it as a function - in short they are functors. The advantage is that it can have a state and depending how you define the operator() you could use the instance of that class as a function. Thse second case is simply a static functionn and does not hold the state in the sense of a class/struct.
第一种情况定义了operator(),因此您可以将它用作函数 - 简而言之它们是函子。优点是它可以具有状态,并且取决于您如何定义operator(),您可以将该类的实例用作函数。第二种情况只是一个静态函数,并不保持类/结构意义上的状态。
#2
0
I suspect the question is related to functors
我怀疑这个问题与仿函数有关
ie you have seen
即你见过
mycompare_instance1(x,y)
vs
VS
mycompare2(x,y)
The first one is a functor. It used where we need to make things that are both objects with state and can be invoked like functions. The second one is a simple function
第一个是仿函数。它用于我们需要制作既是状态对象又可以像函数一样调用的东西。第二个是一个简单的功能