开发者

Error in function sort

I'm trying to use the sort function from STL, but it gives me an error during execution.

My compare function returns true if v is smaller then e:

bool smallerThan(VertexEntry &v, VertexEntry &e) {
   if(v.v[0] < e.v[0]) return true;
   else if(v.v[1] < e.v[1]) r开发者_开发百科eturn true;
   else if(v.v[2] < e.v[2]) return true;
   return false;
} 

and here is the call:

sort(vertices.begin(),vertices.end(),smallerThan);

The size of the vector is aprox 400 elements.

Can somebody help me solve my problem? Thank you!!


Your comparison function is incorrect - it doesn't enforce strict weak ordering.

Use this:

bool smallerThan(VertexEntry const & v, VertexEntry const & e) {
   if (v.v[0] < e.v[0]) 
     return true;
   else if(v.v[0] > e.v[0]) 
     return false;
   else if(v.v[1] < e.v[1]) 
     return true;
   else if(v.v[1] > e.v[1])
     return false;
   else if(v.v[2] < e.v[2])
     return true;
   return false;
} 


Your comparison operator doesn't enforce strict weak ordering. If you're able to use boost one trick I've seen is to bind your object to a boost::tuple and use its strict weak operator<.

If you need to write it yourself, something like this should work:

bool smallerThan(const VertexEntry &v, const VertexEntry &e)
{
   if(v.v[0] != e.v[0]) return v.v[0] < e.v[0];
   else if(v.v[1] != e.v[1]) return v.v[1] != e.v[1];
   else return v.v[2] < e.v[2];
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜