Arp*_*wal 6 c++ stl comparator
我使用struct minHeap使用priority_queue生成最小堆.并使用函数comp以相反的顺序使用STL中给出的sort函数打印数字.现在我的疑问是我不能在函数排序中使用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] << " " ;
}
}
Run Code Online (Sandbox Code Playgroud)
您通常要寻找的是何时使用函数或何时使用仿函数.
简短的回答是:当且仅当您需要在多次调用运算符时保持状态时才使用仿函数.对于比较功能,通常不是这种情况,但还有其他用途实例,如累加器,平均器,最小/最大计算器等.
另一个似乎涵盖类似理由的问题可能会帮助您获得更多细节以及对外部材料的一些很好的参考:比较函数类型与运算符<
至于将实际函数传递给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.
Run Code Online (Sandbox Code Playgroud)
您可以使用仿函数sort(),完全没问题:
sort(arr , arr+4 ,minHeap());
Run Code Online (Sandbox Code Playgroud)
也许你的问题是你只是使用类名(minHeap)而不是函子的实例.minHeap()是对构造函数的调用,而不是operator().
至于priority_queue,具体如下:
template < class T, class Container = vector<T>,
class Compare = less<typename Container::value_type> > class priority_queue;
Run Code Online (Sandbox Code Playgroud)
因此,您需要第三个模板参数的类名(而不是实例).如果要使用函数,必须使用指向函数类型的指针作为第三个模板参数,然后在构造函数中传递函数指针:
priority_queue<int , vector<int> , bool (*)(int a, int b) > b(&comp);
Run Code Online (Sandbox Code Playgroud)