简体   繁体   中英

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. Use std::stable_sort which is most of the times implemented as merge 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 << " " ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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