为什么在C++中编写比较器时,我们会添加括号??
这是一个解释我的意思的代码。
static bool comparator(int a, int b) {
if(a > b) return false;
return true;
}
sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()
Here is a code explaining what I mean.
static bool comparator(int a, int b) {
if(a > b) return false;
return true;
}
sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为我们不是传达调用该功能的结果,而是指向该功能的指针。特别是,第三个参数名为
比较器
tostd :: sort
will 隐式衰减 指向该功能类型由于类型衰减。您可能已经熟悉内置阵列的类型衰减,这也会自动衰减到指向其第一个元素的指针。此(免费功能指针的功能)只是类型衰减的另一个实例。如果我们要通过
comaparator()
,那么我们将传递一个类型bool
的值,这不是预期的。此外,由于比较器
需要2int
参数,因此,如果我们写comparator()
,那将是无效的,因为我们不会传递任何传递任何争论它。它是,好像您写了:
上面修改的语句等同于您在示例中的陈述。这里唯一的句法差异是,这里我们有明确使用
&
来指示我们将指针传递给了一个函数,代码>比较器。Because we're not passing the result of calling that function but instead a pointer to that function. In particular, the third argument named
comparator
tostd::sort
will implicitly decay to a pointer to that function type due to type decay. You might already be familiar with type decay for built in arrays which also automatically decay to a pointer to their first element. This(a free function to function pointer) is just another instance of type decay.If we were to pass
comaparator()
then we would be passing a value of typebool
which is not what is expected. Additionally sincecomparator
takes 2int
arguments and so if we'were to writecomparator()
it would be invalid because we're not passing any argument to it.It is as if you wrote:
The above modified statement is equivalent to the statement that you have in your example. The only syntactic difference here is that here we have explicitly used the
&
to indicate that we're passing a pointer to the function namedcomparator
.如果您要编写
,则意味着必须评估函数
std :: sort
code> comparator()的参数表达式。但是,这两个参数都不提供给函数调用comparator()
。因此,编译器将发出错误消息。另一方面,如果您要编写,
则功能指示器
比较器
将隐式转换为指向函数的指针,并且内部内部的函数std :: sort
本身将调用该功能使用指针并为其提供两个参数。If you will write
then it means that the argument expression of the function
std::sort
comparator()
must be evaluated. But neither arguments are supplied to the function callcomparator()
. So the compiler will issue an error message.On the other hand, if you will write
then the function designator
comparator
is implicitly converted to a pointer to the function and the functionstd::sort
within itself will call the function using the pointer and supplying two arguments to it.