在 c++ 中使用 std::sort 时没有合适的转换错误
No suitable conversion error using while using std::sort in c++
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()
可能是int
或double
,而不是bool
,因此不会有帮助。对于 0 值,它们被转换为 bool
作为false
,否则true
:因此,当输入相等时,您的函数将返回false
,否则true
,这根本不是 std::sort
的比较函数应该是什么样子。小于运算符提供正确的语义。
M.M. 在评论中提出了一个很好的观点——如果clPoint
的x()
方法没有被声明const
,这将不起作用,所以请确保它是(PointGeneric
类声明中的签名应该像 Type x() const;
这样的东西。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- C++使用params创建线程函数会导致转换错误
- 在混合代码库中将C转换为C++时出现许多包含错误
- 为什么g++在未执行的代码处标记强制转换错误
- 错误:从"int"到枚举c++的转换无效
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- 从标准::未来<void>到非标量标准::未来<bool>引发的错误转换
- 使用宏的错误转换
- 在 opencv 中使用 Color_YUV2BGR 从 YUV 到 BGR 的错误转换
- 无法通过此操作,因为类型的错误转换
- PyQt5:使用自定义信号时 int 对象的错误转换
- 从长途错误转换
- C 错误:转换为非量表类型
- C 错误:转换为执行字符集
- 使用SOCI从PostgreSQL数据库获取数据时发生错误转换
- 分段错误C++转换问题
- 在ARM上的Qt中从双精度到QString的错误转换
- C++浮点转换为Python浮点错误转换
- 错误:转换为非标量类型