C++ STL 中的比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12508496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:20:25  来源:igfitidea点击:

Comparators in STL

c++stlcomparator

提问by Arpit Agarwal

I am using struct minHeap to generate a min heap using priority_queue .And function comp to print numbers in reverse order using sort function given in STL . Now my doubt is that I can not use struct minHeap in function sort and can not use function comp in priorityQueue .

我正在使用 struct minHeap 生成一个使用 priority_queue 的最小堆。并且函数 comp 使用 STL 中给出的排序函数以相反的顺序打印数字。现在我的疑问是我不能在函数 sort 中使用 struct minHeap 并且不能在 priorityQueue 中使用函数 comp 。

I feel that function of both struct minHeap and comp is similar. Please explain me when to use structs for comaprator and when to use normal functions to behave as comparators in STL ?

我觉得 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] << " " ;
    }
}

采纳答案by Joris Timmermans

What you are looking for in general is when to use functions or when to use functors.

您通常要寻找的是何时使用函数或何时使用函子

The short answer is: Use a functor if and only if you need to retain state across multiple calls to the operator. For comparison functions this is usually not the case, but there are other instances of uses such as accumulators, averagers, min/max calculators, etc.

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

Another question that seems to cover similar ground and that may help you with more detail and some great references to external material: Comparison Functor Types vs operator<

另一个问题似乎涵盖了类似的领域,可以帮助您提供更多细节和对外部材料的一些重要参考:Comparison Functor Types vs operator<

As to passing an actual function to priority_queue - it's not that obvious but it is possible:

至于将实际函数传递给 priority_queue - 这不是那么明显,但它是可能的:

typedef bool(*CompareFunc)(float, float); // You need to have your function pointer 
                                          // type available
bool Compare(float i_lhs, float i_rhs)    // The actual compare function matching the 
  {                                       // CompareFunc type
  // Do your compare stuff here.
  }

...
std::priority_queue<float, std::vector<float>, CompareFunc> p(Compare);
// Tell priorityqueue you're passing a compare *function*, and pass the actual function
// as a parameter.

回答by Gorpik

You can use a functor in sort(), no problem at all:

您可以在 中使用函子sort(),完全没问题:

sort(arr , arr+4  ,minHeap());

Maybe your problem was that you were just using the class name (minHeap) instead of an instance of the functor. minHeap()is a call to the constructor, not to operator().

也许您的问题是您只是使用类名 ( minHeap) 而不是函子的实例。minHeap()是对构造函数的调用,而不是对operator().

As for priority_queue, it is specified as follows:

至于priority_queue,则指定如下:

template < class T, class Container = vector<T>,
           class Compare = less<typename Container::value_type> > class priority_queue;

Therefore, you need a class name (as opposed to an instance) for the third template argument. If you want to use a function, you must use a pointer to a function type as third template argument and then pass the function pointer in the constructor:

因此,第三个模板参数需要一个类名(而不是实例)。如果要使用函数,则必须使用指向函数类型的指针作为第三个模板参数,然后在构造函数中传递函数指针:

priority_queue<int , vector<int> , bool (*)(int a, int b) > b(&comp);