(B)How should i implement the sorting step using C++ STL (sort function in Algorithm ) Library?Especially i mean sort(P+1,P+N,comparator). How should I define the comparator function?
I suggest you avoid messy floating point arithmetic. As exercise 33.1-3 of the same book points out, you can simply sort by polar angle using cross products. Here is how to do it:
struct Point {int x,y;}
int operator^(Point p1, Point p2) {return p1.x*p2.y - p1.y*p2.x;}
Point p0; //set this separately
bool operator<(Point p1, Point p2)
{
p1=p1-p0; p2=p2-p0;
if(p1.y==0&&p1.x>0) return true; //angle of p1 is 0, thus p2>p1
if(p2.y==0&&p2.x>0) return false; //angle of p2 is 0 , thus p1>p2
if(p1.y>0&&p2.y<0) return true; //p1 is between 0 and 180, p2 between 180 and 360
if(p1.y<0&&p2.y>0) return false;
return (p1^p2)>0; //return true if p1 is clockwise from p2
}
(A)What does this mean,what should i do if more than one points have the same polar angle with respect to Po?
If p0, pi and pj are collinear, only the farthest one from p0, may be part of the convex hull. Thus, we should remove the other points. We can do this in C++. Start by defining the dot product,
int operator*(Point p1, Point p2) {return p1.x*p2.x + p1.y*p2.y;}
and adding this line to the comparator:
if((p1^p2)==0&&p1*p2>0) return p1*p1<p2*p2;
Now in case of same angle, the points will be sorted by distance from p0. Now we can use the unique
function from the STL to remove the points as required from vector<Point> P
:
sort(P.begin(),P.end());
P.erase(unique(P.begin(),P.end(),eq),P.end());
Here, the eq
function returns true if the points have the same angle.
bool eq(Point p1, Point p2)
{
p1=p1-p0; p2=p2-p0;
return ((p1^p2)==0&&p1*p2>0);
}