2012-09-20 75 views
3

我正在使用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] << " " ; 
    } 
} 
+0

可能重複( http://stackoverflow.com/questions/183606/comparison-functor-types-vs-operator) –

回答

6

您在尋找什麼一般是什麼時候使用功能或何時使用functors

簡短的回答是:當且僅當您需要通過對操作員的多次呼叫保留狀態時才使用仿函數。對於比較功能通常不是這種情況,但也有其他用途例如累加器,平均器,最小/最大計算器等。

另一個似乎涵蓋類似的理由,可能會幫助你更詳細的問題和外部材料的一些很好的推薦: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. 
+0

在「priority_queue」示例中使用函數是不可能的,即使在調用之間不存在任何狀態。 – juanchopanza

+0

@ juanchopanza-實際上,您可以 - 它需要一段時間才能找到它,但我現在在編輯中發佈代碼。 –

3

可以在sort()在所有使用函子,沒問題:

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

也許你的問題是,你只是使用類名(minHeap)而不是函子的一個實例。 minHeap()是對構造函數的調用,而不是對operator()的調用。

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

因此,你需要一個類名(而不是一個實例)第三模板參數:

至於priority_queue,它規定如下。如果你想使用的功能,你必須使用一個指針函數類型爲第三個模板參數,然後傳遞函數指針在構造函數中:

priority_queue<int , vector<int> , bool (*)(int a, int b) > b(&comp); 
[比較函子類型與操作<]的
+0

您需要一個類型作爲第三個參數,但該類型可以是一個函數指針類型。 –

+0

@MadKeithV:哦,當然。我正在更新答案。 – Gorpik

+0

Downvote取消:) –