2014-01-16 33 views
1

我讀我的朋友代碼,並來到sort(c + 1, c + n + 1, compare); 其中c是定義爲工作排序功能的C++

class customer { 
public: 
int si; 
int fi; 
int pi; 
}; 

類的客戶對象和寫入功能

bool compare(customer a, customer b) 
{ 
    if (a.pi < b.pi) 
    { 
     return true; 
    } 
    else if (a.pi > b.pi) 
    { 
     return false; 
    } 
    else 
    { 
     return a.fi < b.fi; 
    } 
} 

任何人都可以解釋sort函數是如何工作的,以及這個比較函數是如何與sort函數鏈接的。

+0

應該使用引用和'const'進行比較。即'bool比較(const customer&a,const customer 7b);' –

+1

相反,你應該解釋你不瞭解的內容。 –

+0

@EdHeal我不認爲這是必須的。因爲即使我直接傳遞它也是有效的。 – nomorequestions

回答

2

的std ::排序is defined爲:

template <class RandomAccessIterator, class Compare> 
    void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp); 
// Sorts the elements in the range [first,last) into ascending order. 
// The elements are compared using operator< for the first version, and comp for the second. 

在你的情況,我想c是指客戶的集合中的條目,因爲調用

sort(c + 1, c + n + 1, compare); 

將排序n客戶立即按照收集中的c,使用compare來確定訂單。

std :: sort將使用一些sorting algorithm(可能是大多數實現中的快速排序)爲您執行排序。爲了做到這一點,它需要能夠比較兩個元素。這就是compare功能開始發揮作用:

Binary function that accepts two elements in the range as arguments, 
and returns a value convertible to bool. The value returned indicates 
whether the element passed as first argument is considered to go before 
the second in the specific strict weak ordering it defines. 

在你的情況下,compare功能將在pi升序排序的客戶,以及fi升序(等於pi內)。

2

在C++ std :: sort是一個標準庫函數,通常使用快速排序實現。它是作爲模板函數實現的,並且此重載模板上的比較器的類型,該函數然後將可調用對象作爲第三個參數,並將其用作排序的比較函數。通常這意味着編譯器將能夠將比較函數內聯到排序函數模板的模板實例中,盡​​管它最終可能是一個函數調用。