2011-11-17 115 views
1

我試圖使用STL的sort()中的一類功能。我想排序結構的數組看起來像這樣:比較與STL的sort()

struct foo{ 
    double num; 
    std::string s; 
}; 

有一個比較函數是這樣的:

bool aGreaterThanb(foo a, foo b){ 
    if (a.num > b.num){ 
     if(a.num == b.num){ 
      if (anotherOutsideComparison(a.s, b.s)){ 
       return true; 
      } 
     } 
     else 
      return true; 
    } 
    else 
     return false; 
} 

但我不知道我該怎麼格式化這個得到它編譯。我應該如何格式化以便我可以撥打sort(fooarray[0], fooarray[end], aGreaterThanb);? (一個例子將是巨大的)

+1

它應該按原樣工作。你的代碼中只有一個語法錯誤(在返回true之後,你錯過了一個大括號'}')。對我來說,這是排列開放和關閉大括號的好理由。 –

回答

1

它的工作原理就像你已經想:

#include <algorithm> 
int main() 
{ 
    foo  data[10]; 
    std::sort(&data[0], &data[10], aGreaterThanb); 
} 

但是你有語法錯誤。你缺少一個括號:

 return true; 
} // <--- Missing this line 
else 
    return false; 

爲了提高效率,你應當經常引用:

bool aGreaterThanb(foo const& a, foo const& b){ 
+0

聲明'foo data [10]'的最後一個索引是9,所以,你的聲明應該是'std :: sort(&data [0],&data [9],aGreaterThanb);' –

+3

@Sergio Moura:不。標準算法要求範圍的「結束點」超出範圍的末尾。就像begin()會給你第一個元素,end()會給你一個結束,數據[10]結束。當您在普通數組上使用標準算法時,這是標準明確允許的,並且是必需的。 –

+0

生活和學習。謝謝澄清=) –

2

你應該通過迭代器 - 指針的廣義超 - 到STL sort功能:

std::sort(fooarray, fooarray + end, &aGreaterThanb); 
+0

不論'std :: sort'是否都期望一個小於函數,而不是一個大於函數?我認爲這將是一個問題... –

+0

@PlatinumAzure:它將按降序對數組進行排序。可能這是OP的意圖。 – kennytm

+0

@PlatinumAzure:只要函數/仿函數在elemenets之間提供了一個「嚴格弱」的順序,它應該可以正常工作。 –

5

寫你的比較函數作爲結構的operator()方法稱爲一個算符

struct aGreaterThanb 
{ 
    bool operator() (const foo& a, const foo& b) 
    { 
     // return true iff a is strictly less than b according to your ordering 
    } 
}; 

然後該函子對象的一個​​實例傳遞到std::sort

std::sort(fooarray.begin(), fooarray.end(), aGreaterThanb()); 
+2

隱藏點:通過引用傳遞以避免在每次調用時複製參數 – sehe

+2

函數在std :: sort()中正常工作。就個人而言,我更喜歡使用函子(就像你),但上面的代碼可以不加修改地使用(當語法錯誤被修復時)。見下文。 –

+0

這個答案看起來像是過度殺傷,因爲他不需要狀態。他所做的一切都改爲通過參考。 –

3

如果您正在使用的foo數組是這樣的:

foo fooarray[Foos]; 
... 
sort(fooarray, fooarray + Foos, &aGreaterThanb); 

上面的代碼將您的排序按相反的順序排列,因爲那種期望一個小比較。

此外,以避免將大量的foo -objects只是周圍比較,聲明你比較採取const foo&,而不是foo作爲參數。

bool aGreaterThanb(const foo& a, const foo& b) { 
0

讓它操作。

struct foo { 
    double num; 
    std::string s; 
}; 

bool operator>(const foo& a, const foo& b) { 
    return (
     (a.num > b.num) || 
     ((a.num == b.num) && 
     anotherOutsideComparison(a.s, b.s)) 
    ); 
} 

// note: std::sort expects operator< 
bool operator<(const foo& a, const foo& b) { 
    return b > a; 
} 

如果你真的想使用運營商>進行排序,通過std::greater<foo>()爲仿函數。

std::sort(foos.begin(), foos.end(), std::greater<foo>()); 
+0

'!(a> b)'表示'a <= b'。也許你的意思是'b''''。 – kennytm

+0

@KennyTM:對。 –

+0

甚至'b> a'。 –

0

注意,在最壞的情況下的排序函數爲至多N^2個comparsions。 而stable_sort的複雜度在N * logN和N *之間(LogN^2)