问题描述
在向量上使用STL排序算法时,我想传递自己的比较函数,该函数也带有一个参数.
例如,理想情况下,我想做一个局部函数声明,例如:
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);
}
但是,编译器对此有所抱怨.当我尝试类似的东西时:
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);
}
编译器仍然抱怨:错误:使用包含函数的参数"
我该怎么办?我应该使用全局比较功能来创建一些全局变量吗?
谢谢.
您不能从本地定义的函数中访问函数的局部变量-当前形式的C ++不允许关闭.该语言的下一个版本C ++ 0x将支持此功能,但是该语言标准尚未最终确定,目前对当前的标准草案几乎没有支持.
要执行此操作,应将std::sort
的第三个参数更改为对象实例而不是函数. std::sort
的第三个参数可以是任何可调用的参数(即,在x
中添加x(y, z)
之类的括号在语法上都是有意义的).最好的方法是定义一个实现operator()
函数的结构,然后传递该对象的实例:
struct Local {
Local(int paramA) { this->paramA = paramA; }
bool operator () (int i, int j) { ... }
int paramA;
};
sort(v.begin(), v.end(), Local(paramA));
请注意,我们必须将paramA
存储在结构中,因为否则无法从operator()
内部访问它.
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()
.
这篇关于将参数传递给比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!