在类的成员函数使用带谓词的sort()函数

来源:互联网 发布:决战武林进阶数据灵宠 编辑:程序博客网 时间:2024/05/17 02:08

在类的成员函数内使用带谓词的sort()函数,代码如下:
class Solution {
public:
bool myCompare(int m, int n) {
char str_m[50];
char str_n[50];
sprintf(str_m, “%d”, m);
sprintf(str_n, “%d”, n);
char temp_mn[50];
sprintf(temp_mn, “%d”, m);
strcat(temp_mn, str_n);
char temp_nm[50];
sprintf(temp_nm, “%d”, n);
strcat(temp_nm, str_m);
if(atoi(temp_mn) <= atoi(temp_nm))
return true;
else
return false;
}
string PrintMinNumber(vector numbers) {
string str_res = “”;
if(!numbers.size())
return str_res;
sort(numbers.begin(), numbers.end(), myCompare);

}
};
出现sort() error: reference to non-static member function must be called
原因:sort()函数接受二元谓词,但是在类内定义的myCompare函数作为成员函数,实际上有三个参数,this指针、m、n。
解决方案:
1、将myCompare()函数挪到类定义的外面,即改为非成员函数;
2、将myCompare()函数定义为静态成员函数,没有this指针。
3、将myCompare()函数定义为类的友元函数,但是此时必须在类外声明该函数,否则,即使在类内定义了该友元函数,该函数仍然是不可见的。

原创粉丝点击