如何在 C++ 中调用返回 bool 并具有两个 int 参数的函数而没有其参数?

2022-01-19 00:00:00 function boolean c++

我正在使用 std::sort 对数组进行降序排序.

#include <iostream>#include <算法>#定义尺寸 5使用命名空间标准;布尔降序(int x,int y){返回x>y;}诠释主要(){int a[大小]={5,3,7,34,2};排序(a,a+大小,降序);返回0;}

此代码有效.但我不知道为什么.

  1. 不应该使用 2 个参数调用降序吗?

解决方案

这里你不是在你的程序中调用 descending() 函数,你是把它传递给 std::sort() 作为 函数指针 接受类型的函数指针

bool cmp(const Type1 &a, const Type2 &b);

作为它的第三个参数.


根据 cppreference , std::sort 的第三个参数是comp

<块引用>

比较函数对象(即满足Compare要求的对象) 如果第一个参数小于(即排在前面)第二个参数,则返回真.比较函数的签名应该等价于:

<块引用>

bool cmp(const Type1 &a, const Type2 &b);

<块引用>

虽然签名不需要 const &,但该函数不得修改传递给它的对象,并且必须能够接受所有类型(可能是 const)Type1 和 Type2 的值,而不管值类别如何(因此,Type1& 是不允许的,Type1 也是不允许的,除非 Type1 的移动等价于一个副本(C++11 起)).

<块引用>

Type1 和 Type2 类型必须使得 RandomIt 类型的对象可以被取消引用,然后隐式转换为它们两者.

来源:

std::sort

I am using std::sort to sort an array in descending order.

#include <iostream>
#include <algorithm>
#define size 5
using namespace std;

bool descending(int x,int y){
    return x>y;
} 
int main(){
    int a[size]={5,3,7,34,2};
    sort(a,a+size,descending);
    return 0;
}

This code works. But I'm not sure why.

  1. Shouldn't descending be called with 2 arguments?

解决方案

Here you are not calling descending() function in your program, you are passing it to std::sort() as a function pointer which accepts a function pointer of type

bool cmp(const Type1 &a, const Type2 &b);

as its third argument.


according to cppreference , the third argument to std::sort is comp which is

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ?true if the first argument is less than (i.e. is ordered before) the second. The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1 &a, const Type2 &b);

While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy (since C++11)).

The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ?

source :

std::sort

相关文章