I have a vector of structs and I need help with how to sort them according to one of the values, and if those 2 values are the same, then sort it according to another parameter.
This is similar to other questions, but it has more to it.
What I am trying to implement is the scan line based polygon fill algorithm.
I build the active edge list, but then I need to sort it based on the x value in each struct object. If the x values are the same, then they need to be sorted based on the inverse of the slopes for each struct object.
Here is the definition of the struct with the override operator < for normal sorting:
struct Bucket
{
// Fields of a bucket list
int ymax, x, dx, dy, sum;
// Override the < operator, used for sorting based on the x value
bool operator < (const Bucket& var) const
{
// Check if the x values are the same, if so
// sort based on the ivnerse of the slope (dx/dy)
/*if(x == var.x)
return (dx/dy) < (var.dx/var.dy);
else*/
return (x < var.x);
}
};
I commented out the if then else statement because it does compile, but causes a floating point error and the program crashes.
The exact error is: “Floating point exception (core dumped)”
I also tried casting each division to (int) but that did not work either.
My question: Is there a way to do the sort similar to the way I have it, or should I write my own sort method.
If I should make my own sort method, please provide a link or something to a simple method which can help.
Thanks
You should implement double division, because with integers, when you have for example 5/6 it results in 0, and division by 0 is not possible as we know. That’s why the program crashes.
SO change the members of the structure to doubles.And then you should take care of some precision issues but at least the program won’t crash assuming that you are not allowing 0 value for dy.