Passing a parameter to a comparison function?

comparator function
comparator c++
std::sort
sort compare function
static comparison function
c++ binary search custom compare
stable_sort comparator
c++ sort lambda

When using the STL sort algorithm on a vector, I want to pass in my own comparison function which also takes a parameter.

For example, ideally I want to do a local function declaration like:

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    bool comp(int i, int j) {
        // logic uses paramA in some way...
    }

    sort(v.begin(), v.end(), comp);
}

However, the compiler complains about that. When I try something like:

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    struct Local {
        static bool Compare(int i, int j) {
            // logic uses paramA in some way...
        }
    };

    sort(v.begin(), v.end(), Local::Compare);
}

The compiler still complains: "error: use of parameter from containing function"

What should I do? Should I make some global variables with a global comparison function..?

Thanks.

You cannot access the local variables of a function from within a locally defined function -- C++ in its current form does not allow closures. The next version of the language, C++0x, will support this, but the language standard has not been finalized and there is little support for the current draft standard at the moment.

To make this work, you should change the third parameter of std::sort to be an object instance instead of a function. The third parameter of std::sort can be anything that is callable (i.e. any x where adding parentheses like x(y, z) makes syntactic sense). The best way to do this is to define a struct that implements the operator() function, and then pass an instance of that object:

struct Local {
    Local(int paramA) { this->paramA = paramA; }
    bool operator () (int i, int j) { ... }

    int paramA;
};

sort(v.begin(), v.end(), Local(paramA));

Note that we have to store paramA in the structure, since we can't access it otherwise from within operator().

Passing a parameter to a comparison function? - c++ - android, You cannot access the local variables of a function from within a locally defined function -- C++ in its current form does not allow closures. The next version of the​  Parameter Passing Techniques in C/C++ There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A() .

In C++ you cannot define a free function inside another function. So your first code snippet is ill formed.

sort(v.begin(), v.end(), Local::Compare);

The 3rd argument must be a function object. Overload () operator inside the class and then create the function object.


In C++0x you can use lambda expressions.

auto comp = [&](int m,int n)-> bool {

        return m<n; //or use paramA in some way
    };

sort(v.begin(), v.end(), comp);

Passing extra parameters to STL sort, When using the STL sort algorithm on a vector, I want to pass in my own comparison function which also takes a parameter. For example, ideally I want to do a  Passing a function as a parameter to another function I'm brand new to TypeScript/Angular so forgive my lack of clarity in my explanation but I'm having trouble figuring out if this scenario is possible.

One possibility is to pass the parameter when you construct your comparator object:

class cmp {
    int param;
public:
    cmp(int p) : param(p) {}

    bool operator()(int i, int j) {
        // logic uses param
    }
};

int main() {
    vector<int> v(100);
    // initialize v with some random values

    int paramA = 4;

    sort(v.begin(), v.end(), cmp(paramA));
}

Functors - Function Objects in C++, But traditionally, a comparator function takes in only 2 arguments of the implement to () operator function, while passing the extra arguments  Parameters and Arguments. Information can be passed to functions as a parameter. Parameters act as variables inside the function. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:

//Using std::bind

//Example

{
vector<int> vecInt{2, 4, 10, 20, 30};
    int i = 4;
    sort(vecInt.begin(), vecInt.end(), std::bind( [](int a, int b, int c)
    {
        return abs(a - c) < abs(b - c);
    }, std::placeholders::_1, std::placeholders::_2, i)
    );
}

STL Sort Comparison Function, What you'd really like is the ability to pass in a third argument to your comparison function, telling it which field to look at. But to make this work, you'd have to  In C programming you can only pass variables as parameter to function. You cannot pass function to another function as parameter. But, you can pass function reference to another function using function pointers. Using function pointer you can store reference of a function and can pass it to another function as normal pointer variable. And finally in the function you can call function pointer as normal functions.

3 Ways to Define Comparison Functions in C++, Writing comparison function for std::sort. _1 and _2 are the 2 integer arguments passed to the Lambda comparison function. Note: as seen in the earlier  When passing functions around to other functions things are however not as straightforward as they might sound. Should you use a template parameter? Should you use std::function? A function pointer? This article aims to compare the aforementioned function-passing techniques and to provide some guidelines. Every technique will benchmarked.

How to pass a function as an argument to another function in c++ , You can use comparison function for STL containers by passing them as Now, you pass this class as a template argument to STL containers. Passing an argument by address involves passing the address of the argument variable rather than the argument variable itself. Because the argument is an address, the function parameter must be a pointer. The function can then dereference the pointer to access or change the value being pointed to.

Comparison Functions (The GNU C Library), You can pass a function by reference or as a pointer (and in fact if you write a U can pass an comparison function as a third argument in sort function and u  The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.

Comments
  • The third parameter is anything that can be called using function call syntax. So both a function and a class/struct that defines operator() will do the trick.
  • Thanks, that's working (except that the compiler complains unless I move the struct declaration outside the main function. I thought we were allowed to declare classes and structs locally..?)
  • This should work. Try posting a separate question about those complaints.
  • Can the same thing be done with std::map? If so, how would the syntax be for passing an instance of the struct to the map?
  • In my opinion a much better solution than the excepted one because of using nice c++ features (lambda)
  • This was asked before std::bind (and lambdas) was part of the standard. And it's much simpler to have a capturing lambda than binding a non-capturing lambda