c++ - STL 中的比较器

标签 c++ stl comparator

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

感觉struct minHeap和comp的功能差不多。请解释一下何时使用比较器的结构以及何时使用普通函数作为 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] << " " ;
    }
}

最佳答案

您通常要查找的是何时使用函数或何时使用 functors .

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

另一个问题似乎涵盖了类似的领域,可能会帮助您了解更多细节和一些对外部 Material 的重要引用:Comparison Functor Types vs operator<

关于将实际函数传递给 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.

关于c++ - STL 中的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12508496/

相关文章:

c++ - 在函数中创建的对象的范围

c++ - 跳过迭代器

java - 使用自定义排序功能实现 Treeset

java - 使用运行时提供的属性动态对列表进行排序

java - "Comparison method violates its general contract!"

c++ - 相机跟随播放器opengl

c++ - 基于范围的实现在 g++ 中编译但在 clang++ 中不编译

java - 传递给 C 的 JNI 回调

c++ - 更改 C++ vector 的保留内存

c++ - 写入字符串流后,为什么提取到字符串中会导致该字符串变成伪造的?