这是解释我的意思的代码。
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()
写的时候为什么不加括号comparator
in c++?
因为我们没有传递调用该函数的结果,而是传递指向该函数的指针。特别是,第三个参数名为comparator
to std::sort
will 隐式衰退 to a 指向该函数类型的指针 due to 类型衰减。您可能已经熟悉内置数组的类型衰减,它也会自动衰减为指向其第一个元素的指针。这(函数指针的自由函数)只是类型衰减的另一个实例。
如果我们要通过comaparator()
那么我们将传递一个类型的值bool
这不是我们所期望的。另外自从comparator
需要 2int
参数,所以如果我们要写comparator()
它是无效的,因为我们没有向它传递任何参数。
It is 就像你写的一样:
//---------------------------v--------------->note the & operator used here which is optional
sort(arr.begin(), arr.end(), &comparator); //this statement is equivalent to the statement that you have in your question
上面修改后的语句与示例中的语句等效。唯一的句法差异这是我们这里明确地使用了&
表明我们正在传递一个指向名为的函数的指针comparator
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)