在 c++ 中使用 std::sort 时没有合适的转换错误

No suitable conversion error using while using std::sort in c++

本文关键字:错误 转换 sort c++ std      更新时间:2023-10-16
bool COMPARE(const void * i, const void * j) 
{ return (((clPoint*)i)->x() - ((clPoint*)j)->x()); }

std::vector<clPoint> iFillPoints;

std::sort(iFillPoints.begin(), iFillPoints.end(), COMPARE);

运行此命令时出现此错误

Error   16  error : no suitable conversion function from "Pixel" to "const void *" exists   

你的compare函数可能看起来更像

bool COMPARE(const clPoint& i, const clPoint& j) 
{ return i.x() < j.x(); }

std::sort算法将传入容器的元素,这些元素是clPoint,而不是指针(当然也不是空指针(。您可以通过引用而不是值接受clPoint对象。这也消除了放弃空指针的需要。

该函数应返回一个bool; 您最初拥有的i.x() - j.x()可能是intdouble,而不是bool,因此不会有帮助。对于 0 值,它们被转换为 bool 作为false,否则true:因此,当输入相等时,您的函数将返回false,否则true,这根本不是 std::sort 的比较函数应该是什么样子。小于运算符提供正确的语义。

M.M. 在评论中提出了一个很好的观点——如果clPointx()方法没有被声明const,这将不起作用,所以请确保它是(PointGeneric类声明中的签名应该像 Type x() const; 这样的东西。