How to pass parameter to sort's compare function?

Viewed 85

I want to sort a vector v using this

std::sort(v.begin(),v.end(),cmpr);

where my cmpr function is

bool cmpr(int a,int b, int c) 
{
     return a%c <= b%c;
}

now i want to know how can i pass c?

1 Answers

You can use a lambda to wrap your comparator. A full example:

#include <algorithm>
#include <iostream>

auto make_cmpr(int c)
{
    return [c](int a, int b) {
        return a%c <= b%c;
    };
}

int main()
{
    int a[5] = {2, 4, 1, 3, 5};
    std::sort(a, a + 5, make_cmpr(3));

    /* or directly
    int c = 3;
    std::sort(a, a + 5, 
        [c](int a, int b) {
            return a%c <= b%c;
        }
    );
    */

    for (int e : a) std::cout << e << ' ';
}
Related