今天调用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; }