调用STL的sort,出错提示invalid

今天调用STL的sort函数,结果一直出错说 invalid < ,网上找了很久都没有找到相关解答,弄了许久终于弄明白为啥。。举个例子如下,注意下面的比较函数ComparePoint,当要比较的两个元素相等的时候,返回true:

class TrajPoint
{
public:
	double distance;
	int edgeId;
};

bool ComparePoint(TrajPoint a,TrajPoint b)
{
	if(a.distance<b.distance)
		return true;
	if(a.distance==b.distance)
		return true;
	return false;
}

int main()
{
  ...........
  sort(vec.begin(),vec.end(),ComparePoint);
  ............
}

原来是vs2008和vs2010后都是严格比较,相等的两个元素,一定要返回false,可以看到STL的源码:

template<class _Pr, class _Ty1, class _Ty2> inline
	bool _Debug_lt_pred(_Pr _Pred,
		_Ty1& _Left, _Ty2& _Right,
		_Dbfile_t _File, _Dbline_t _Line)
	{	// test if _Pred(_Left, _Right) and _Pred is strict weak ordering
	if (!_Pred(_Left, _Right))
		return (false);
	else if (_Pred(_Right, _Left))
		_DEBUG_ERROR2("invalid operator<", _File, _Line);
	return (true);
	}

如果left和right都一样,STL就会报错。。所以只能修改下自己的代码,当相等的时候,就返回false了。问题解决。

bool ComparePoint(TrajPoint a,TrajPoint b)
{
	if(a.distance<b.distance)
		return true;
	return false;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值