自定义std::sort的比较函数时发生"invalid operator<"错误原因(转载)

原始自定义函数:

//输入:Rect a 和 Rect b
//输出:当a的面积小于b的面积时输出1
int Frame_Method::cmp_func_area(const CvRect&a,const CvRect&b)
{  
 return (a.width*a.height)>(b.width*b.height)? -1 : (a.width*a.height)<(b.width*b.height) ? 1:0;
}

这种方式下提示有上述错误“invalid operator<”。

修改后:

int Frame_Method::cmp_func_area(const CvRect&a,const CvRect&b)
{  
  return (a.width*a.height)>(b.width*b.height); //逻辑表达式正确返回(ture即非零值),错误返回(false即0)
}

这样就正确了;

原因:

上述程序错误原因:a>b时返回ture,ab时返回ture,其它(小于等于)都是false

VS2005,VS2008后的sort()里,用的是所谓的“ strict weak ordering”,也就是说,如果a==b,则返回的应该是false,如果返回的是true,则会出上面的错。

1、出现"Expression : invalid operator <"的写法
bool CustPredicate (int elem1, int elem2 )
{
    if(elem1 > elem2)
       return true;

    if (elem1 < elem2)
       return false;
    return true;
}
2、为了解决错误,应把以上代码改写为以下两种中的任一种:
(1)
bool CustPredicate (int elem1, int elem2 )
{
    if(elem1 > elem2)
       return true;

    if (elem1 < elem2)
       return false;

   return false; //Should return false if both the vaules are same
}

(2)

bool CustPredicate (int elem1, int elem2 )
{
    return elem1 > elem2;
}

猜你喜欢

转载自www.cnblogs.com/willowcc1803/p/12342926.html