Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 优先级队列lambda比较器和普通比较器 #包括 #包括 #包括 #包括 使用名称空间std; 自动cmp2(常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; } int main(){ 自动cmp=[](常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; }; 优先级队列pq(cmp); 优先级队列pq2(cmp2); }_C++_Stl_Comparator_Priority Queue - Fatal编程技术网

C++ 优先级队列lambda比较器和普通比较器 #包括 #包括 #包括 #包括 使用名称空间std; 自动cmp2(常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; } int main(){ 自动cmp=[](常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; }; 优先级队列pq(cmp); 优先级队列pq2(cmp2); }

C++ 优先级队列lambda比较器和普通比较器 #包括 #包括 #包括 #包括 使用名称空间std; 自动cmp2(常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; } int main(){ 自动cmp=[](常量数组和a、常量数组和b){ 返回a[0]+a[1]>b[0]+b[1]; }; 优先级队列pq(cmp); 优先级队列pq2(cmp2); },c++,stl,comparator,priority-queue,C++,Stl,Comparator,Priority Queue,主函数中有一个lambda比较器,外部有另一个比较器。为什么只有第一个优先级队列可以编译,而第二个优先级队列不能编译,并给出了一个无效声明函数类型的错误。 提前谢谢。cmp是lambda。它是一个带有()操作符的对象 但是cmp2()是一个函数 不能将函数用作可调用类型,但可以将函数指针用作可调用类型,在这种情况下,必须使用decltype(&cmp)获取函数指针类型: #include <iostream> #include <queue> #include <v

主函数中有一个lambda比较器,外部有另一个比较器。为什么只有第一个优先级队列可以编译,而第二个优先级队列不能编译,并给出了一个无效声明函数类型的错误。
提前谢谢。

cmp
是lambda。它是一个带有
()
操作符的对象

但是
cmp2()
是一个函数

不能将函数用作可调用类型,但可以将函数指针用作可调用类型,在这种情况下,必须使用
decltype(&cmp)
获取函数指针类型:

#include <iostream>
#include <queue>
#include <vector>
#include <array>
using namespace std;

auto cmp2(const array<int, 2>& a, const array<int, 2>& b) {
    return a[0]+a[1] > b[0]+b[1];
}

int main() {
    auto cmp = [] (const array<int, 2>& a, const array<int, 2>& b) {
        return a[0]+a[1] > b[0]+b[1];
    };

    priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp)> pq(cmp);

    priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(cmp2)> pq2(cmp2);
}
priority_队列pq2(&cmp2);

那么为什么主函数中的cmp起作用,难道不是一个函数吗?
cmp
是一个lambda,它是一个带有
操作符()
的类的实例。谢谢你的回答!在问这类问题之前,我应该更深入地研究。这两个例子都需要
decltype
吗?@sweenish
decltype
需要获取类型,并且需要
decltype(&cmp2)
,因为比较参数默认为
std::less
    priority_queue<array<int, 2>, vector<array<int, 2>>, decltype(&cmp2)> pq2(&cmp2);