自定义std::sort的比较函数时发生"…

原始自定义函数:

//输入: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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值