2

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?

aditya rai
  • 67
  • 6
  • you're looking for `std::bind` – fas Mar 30 '20 at 04:31
  • 4
    As mentioned you can use [`std::bind`](https://en.cppreference.com/w/cpp/utility/functional/bind), or create a [*functor* object](https://stackoverflow.com/questions/356950/what-are-c-functors-and-their-uses) with `c` as a member that's initialized on construction. You could also use a [lambda expression](https://en.cppreference.com/w/cpp/language/lambda). – Some programmer dude Mar 30 '20 at 04:37
  • 1
    Even if you got your code to work, your comparison function does not follow a `strict-weak-ordering`, as you're returning `true` or `false` for equal values of `a` and `b`. So you need to fix that also. – PaulMcKenzie Mar 30 '20 at 05:15

1 Answers1

3

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 << ' ';
}
xskxzr
  • 12,442
  • 12
  • 37
  • 77