C++ STL中的比较器

C++ STL中的比较器,c++,stl,comparator,C++,Stl,Comparator,我使用structminheap生成一个使用优先级队列的最小堆,并使用STL中给出的排序函数comp以相反顺序打印数字。现在我的疑问是,我不能在函数排序中使用struct minHeap,也不能在priorityQueue中使用comp函数 我觉得struct minHeap和comp的功能是相似的。请解释一下什么时候使用结构作为comaprator,什么时候使用普通函数作为STL中的比较器 #include<iostream> #include <queue> #inc

我使用structminheap生成一个使用优先级队列的最小堆,并使用STL中给出的排序函数comp以相反顺序打印数字。现在我的疑问是,我不能在函数排序中使用struct minHeap,也不能在priorityQueue中使用comp函数

我觉得struct minHeap和comp的功能是相似的。请解释一下什么时候使用结构作为comaprator,什么时候使用普通函数作为STL中的比较器

#include<iostream>
#include <queue>
#include <stdio.h>
#include<algorithm>
using namespace std;

struct minHeap
{
    bool operator()(const int a , const int b )
    {
        return a>b;
    }
};
bool comp(int a , int b)
{
    return a>b;
}

int main()
{
    priority_queue<int , vector<int> , minHeap > b;

    b.push(4);
    b.push(23);
    b.push(12);
    while(b.size()!=0)
    {
        cout << b.top() << " " ;
        b.pop();
    }
    cout<<"\n" ;
    int arr[] = {12,34, 112,12};
    sort(arr , arr+4  ,comp);

    for(int x= 0 ; x < 4 ; x++)
    {
        cout << arr[x] << " " ;
    }
}
#包括
#包括
#包括
#包括
使用名称空间std;
结构minHeap
{
布尔运算符()
{
返回a>b;
}
};
布尔公司(内部a、内部b)
{
返回a>b;
}
int main()
{
优先级队列b;
b、 推(4);
b、 推(23);
b、 推(12);
而(b.大小()!=0)
{

cout您通常需要的是何时使用函数或何时使用

简单的回答是:当且仅当需要在多次调用运算符时保留状态时,才使用函子。对于比较函数,通常情况并非如此,但还有其他使用实例,如累加器、平均器、最小/最大计算器等


另一个问题似乎涵盖了类似的领域,它可能会帮助您了解更多细节和外部材料的一些重要参考:比较函子类型与运算符您可以在
sort()
中使用函子,一点问题也没有:

sort(arr , arr+4  ,minHeap());
可能您的问题是您只是使用了类名(
minHeap
)而不是functor的实例。
minHeap()
是对构造函数的调用,而不是对
操作符()
的调用

对于
优先级\u队列
,其规定如下:

template < class T, class Container = vector<T>,
           class Compare = less<typename Container::value_type> > class priority_queue;
template类优先级\u队列;
因此,第三个模板参数需要一个类名(与实例相反)。如果要使用函数,必须使用指向函数类型的指针作为第三个模板参数,然后在构造函数中传递函数指针:

priority_queue<int , vector<int> , bool (*)(int a, int b) > b(&comp);
优先级\u队列b(&comp);

比较函子类型与运算符的可能重复在
优先级队列
示例中使用函数是不可能的,即使调用之间没有状态可保留。@juanchopanza-实际上可以-查找它花了一段时间,但我现在正在编辑中发布代码。
priority_queue<int , vector<int> , bool (*)(int a, int b) > b(&comp);