[英]merge sort with a comparator and a vector as arguments
我遇到的問題涉及編寫使用合並排序對向量進行排序的函數,我還需要使用函子。 如何將比較器/函數用作合並排序函數對矢量進行排序的參數?
您可以這樣定義比較運算符
struct MyLessThanFunctor
{
bool operator() (int i,int j)
{
return (i<j);
}
};
然后,實例化並使用它
MyLessThanFunctor comparator;
sort(elements, comparator);
!!!警告std :: sort不應是穩定的排序算法。 使用std :: stable_sort,大多數情況下它是作為合並排序實現的。
struct comparator
{
bool operator () (int i1, int i2) const { return i1 < i2; }
};
int main()
{
vector<int> v = {0,13,76,46,53,22,4,68,68,94,38,52,83,3,5,53,67 };
std::stable_sort (v.begin(), v.end(), comparator() );
for (auto e : v) cout << e << " " ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.