I don't entirely agree with answer, but the basic point is close to correct.
You need a "point" class:
1 2 3 4 5 6 7
|
struct point
{
double x;
double y;
point(): x( 0.0 ), y( 0.0 ) { }
point( double x, double y ): x( x ), y( y ) { }
};
|
This lets you store your points as individual things:
1 2 3 4 5 6
|
vector <point> points;
points.push_back( point( 1, 1 ) );
points.push_back( point( 2, 2 ) );
...
points.push_back( point( 5, 1 ) );
|
Now for the sorting. You wish to "[sort] 2D points clockwise". If that means what I think it means, then I assume you have a list of points like the following:
^ y
|
| *
|
* |
| *
----------+----------> x
* |
|
|
|
|
|
When sorted, they will be ordered like the following:
^ y = 12 o'clock
|
| *p1
p4 |
* |
| *p2
----------+----------> x
* |
p3|
|
|
|
|
In order to do this, you must compare the
angles that each point is from 12 o'clock:
^ y /
| /
| *p1
p4 | /
* |a/
|/ *p2
----------+----------> x
* |
p3|
|
|
|
|
This requires some basic trigonometry, specifically, using the tangent formula:
opposite = x
tan a = --------------
adjacent = y
|
Since you know x and y, you can rewrite using the arctangent. Amazingly enough, C and C++ have a two-argument arctangent function in <cmath>:
http://www.cplusplus.com/reference/cmath/atan2/
Remember, the angle is measured from 12:00, so we've
switched the y and x.
Call
atan() with
atan( p.x, p.y )
.
Remember also that
atan() has limitations, so you must write your code to account for the quadrant of your point.
Again, the most difficult thing will be remembering that by requiring it to be "clockwise" you have changed from the standard cartesian system to a custom one -- meaning that you must convert between the custom and standard when using the standard math functions.
When you compile, you will also have to link in the standard C math library.
I recommend you write yourself a function that takes a point and returns the clockwise angle from 12:
1 2 3 4 5 6 7
|
double clockwise_angle_of( const point& p )
{
// (1) figure out point's quadrant
// (2) call atan() properly for the quadrant to get the angle
// (3) add the appropriate pi/2 value (one of 0, pi/2, pi, 3pi/2, depending on the quadrant) to the angle
// (4) return the angle
}
|
So when you finally figure that out (good luck!), then you can sort. As you don't have too many points, you might as well just calculate the angles in your sort function's comparison function.
1 2 3 4
|
bool clockwise_compare_points( const point& a, const point& b )
{
return clockwise_angle_of( a ) < clockwise_angle_of( b );
}
|
Sorting the list of points then becomes simply:
|
std::sort( points.begin(), points.end(), clockwise_compare_points );
|
And displaying the result:
1 2
|
for (size_t n = 0; n < points.size(); n++)
cout << "(" << points[n].x << "," << points[n].y << ")\n";
|
Hope this helps.