Passing a parameter to a comparison function?

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().

Leave a Comment