[英]Comparison with 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);
? (一個很好的例子)
將比較函數編寫為稱為函子的結構的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());
如果您使用這樣的foo
數組:
foo fooarray[Foos];
...
sort(fooarray, fooarray + Foos, &aGreaterThanb);
上面的代碼將以相反的順序對數組進行排序,因為sort需要小於比較器。
另外,為了避免為了比較而復制大量foo
-object,請聲明比較器以const foo&
而不是foo
作為參數。
bool aGreaterThanb(const foo& a, const foo& b) {
您應該將迭代器(指針的通用超集)傳遞給STL sort
函數:
std::sort(fooarray, fooarray + end, &aGreaterThanb);
它就像您已經想要的那樣工作:
#include <algorithm>
int main()
{
foo data[10];
std::sort(&data[0], &data[10], aGreaterThanb);
}
但是您有語法錯誤。 您缺少括號:
return true;
} // <--- Missing this line
else
return false;
為了提高效率,您應該通過const引用:
bool aGreaterThanb(foo const& a, foo const& b){
使其成為運算符。
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;
}
如果您真的想使用operator>進行排序,請傳遞std::greater<foo>()
作為函子。
std::sort(foos.begin(), foos.end(), std::greater<foo>());
請注意,在最壞的情況下,排序函數的比較次數最多為N ^ 2。 而且stable_sort的復雜度在N * logN和N *(LogN ^ 2)之間
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.