我正在使用struct minHeap來使用priority_queue生成最小堆。並且函數comp使用STL中給出的排序函數以相反順序打印數字。現在我懷疑我不能在函數sort中使用struct minHeap,並且不能在priorityQueue中使用function comp。STL中的比較器
我覺得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] << " " ;
}
}
可能重複( http://stackoverflow.com/questions/183606/comparison-functor-types-vs-operator) –