简体   繁体   English

使用比较器和向量作为参数合并排序

[英]merge sort with a comparator and a vector as arguments

The issue I'm having involves writing a function to use merge sort to sort a vector, and I need to use a functor as well. 我遇到的问题涉及编写使用合并排序对向量进行排序的函数,我还需要使用函子。 How can a comparator/functor be used as an argument to the merge sort function to sort a vector? 如何将比较器/函数用作合并排序函数对矢量进行排序的参数?

You could define a comparisor operator like this 您可以这样定义比较运算符

struct MyLessThanFunctor
{
    bool operator() (int i,int j)
    {
    return (i<j);
    }
};

And after that, instancing it and using it 然后,实例化并使用它

MyLessThanFunctor comparator;
sort(elements, comparator);

!!!Warning std::sort is not expected to be a stable sorting algorithm. !!!警告std :: sort不应是稳定的排序算法。 Use std::stable_sort which is most of the times implemented as merge 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM