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::sortto be an object instance instead of a function. The third parameter ofstd::sortcan be anything that is callable (i.e. anyxwhere adding parentheses likex(y, z)makes syntactic sense). The best way to do this is to define a struct that implements theoperator()function, and then pass an instance of that object:Note that we have to store
paramAin the structure, since we can’t access it otherwise from withinoperator().