C++ 自定义类的sort 重写比较函数,出错 了,大神求现身
本帖最后由 tortoisedream 于 2013-06-19 22:24:29 编辑 现在在用mfc写大作业,遇到重写sort比较函数的问题
定义类
class final
{
public:
CString a;
double b;
};
这个是重写函数:
bool CSort::compare(final *v1, final *v2)
{
return (v1->b > v2->b);
}
这个是调用:
std::sort(f[0],f[count+1],compare);
count是我数组的长度,前面已经初始化完了
问题:
error C2664: 'void __cdecl std::sort(class CSort::final *,class CSort::final *,bool (__thiscall *)(class CSort::final *,class CSort::final *))' : cannot convert parameter 3 from 'bool (class CSort::
final *,class CSort::final *)' to 'bool (__thiscall *)(class CSort::final *,class CSort::final *)'
None of the functions with this name in scope match the target type
求大神帮忙,顺便可否解释下原理,感谢,或者提供能给自定义类的比较某个值的方法~~ c++ MFC 重写sort比较函数
[解决办法]
f 是什么?
如果f是final*或是final[]
则:
class CSort
{
public:
static bool compare(final const & v1, final const & v2);
//std::sort要求函数对象,或是静态/全局函数指针
//非静态成员函数指针不能直接传递给std::sort
};
bool CSort::compare(final const & v1, final const & v2)
{
return (v1.b > v2.b);
}
这个是调用:
std::sort(&f[0],&f[count],CSort::compare);
//[ ]会消引用,所以要加上&操作符。
//count是数量就不要加1 ,是下标上界就加1
class final_compare
{
public:
bool operator()(final const * v1, final const * v2)const;
//这回用函数对象演示
};
bool final_compare::operator()(final const * v1, final const * v2) const
{
return (v1->b > v2->b);
}
//调用还是要加&,构造一个函数对象代替函数指针
std::sort(&f[0],&f[count],final_compare());
class final
{
public:
CString a;
double b;
static bool compare (final *v1, final *v2)
{
return (v1->b > v2->b);
};
};
int main ()
{
final* f [50];
std::sort(f,f+50,final::compare);
}