我自己写了一个sort()的比较函数.当我这样说时,它运作良好.
bool comp(string a, string b)
{
...;
}
int main()
{
sort(...,...,comp);
}
Run Code Online (Sandbox Code Playgroud)
但是,当我把所有这些都放在一个班级时,说:
class Test {
public:
bool comp(string a,string b)
{
...;
}
vector <string> CustomSort(vector <string> str) {
sort(...,...,comp);
}
};
Run Code Online (Sandbox Code Playgroud)
有一个编译错误"没有匹配函数来调用'sort ......'.
为什么会这样?
类的任何非静态成员函数X
具有一个额外的参数-参考/指针(const
)X
成为this
.因此,成员函数的签名不是可以被消化的sort
.你需要使用boost::bind
或std::mem_fun
或std::mem_fun_ref
.使用C++ 11时,您可以使用std::bind
.
std::sort(..., ..., std::bind(&Test::comp, this, _1, _2));
Run Code Online (Sandbox Code Playgroud)
想想看,在这种情况下,最好的解决方案是使你的comp函数保持静态,因为它根本不需要this
.在这种情况下,您的原始代码将无需更改即可运行
归档时间: |
|
查看次数: |
1067 次 |
最近记录: |