Sort points in vector to form conture
<p>I got a vector with n rows with xy coordinates of points. These points form a conture of an given CAD model. Now I want to restore the conture of the model. So I tried to sort the point with the atan2 function.
This is the code I use to sort the points.</p>

<pre><code>std::sort(matrix.begin(), matrix.end(), sort1);

matrix.erase(std::unique(matrix.begin(), matrix.end(), compare2),matrix.end());

matrix.push_back(std::vector&lt;double&gt;(3, 0));
</code></pre>

<p>So first I sort the points in the vector matrix. As compare function i use this code</p>

<pre><code>bool sort1(vector&lt;double&gt; const&amp; s1, vector&lt;double&gt; const&amp; s2)
{
    return atan2(s1[1],s1[0])&lt;atan2(s2[1],s2[0]);
} 
</code></pre>

<p>After the vector has been sorted, I just delete duplicates to reduce the size of the vector. The last step is to push back the first point to the end of the vector to close the conture.
For standard models like a cube, or a ball this works fine, but for more complicate models the atan2 function is note working fine.
So this image show the unsorted points.
<a href="https://i.stack.imgur.com/c3dDX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c3dDX.png" alt="Picture of unsorted points"></a></p>

<p>When I sort the vector I get this conture as result
<a href="https://i.stack.imgur.com/RmYuv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RmYuv.png" alt="enter image description here"></a></p>

<p>My first approach was to check the atan2 function but it's working fine. The problem seem to be the result of the atan2 function. So this list shows the actual coordinates and the result of the atan2 function</p>

<pre><code>   x             y      z     atan2
-5.44283    -1.94995    0   -2.79758
-5.36969    -1.93228    0   -2.79617
-5.33637    -1.92454    0   -2.79547
-13.15      -4.76500    0   -2.79395
-5.26308    -1.90750    0   -2.79389
-5.22970    -1.90005    0   -2.7931
-5.15626    -1.88364    0   -2.79134
</code></pre>

<p>As you can see while the x and y coordinate change the atan2 stays in the same range as the other values. For me that's the problem, why my conture isn't correct. Do I have to add something to my sort function to get the correct results? </p>

<p>One idea i had was to sort the coordinates not just by the atan2, but also by the length of the vector between the point, with the lowest atan2, and all other points. But here's my problem. I would first sort by atan2, and then sort again by the length. But the second sort process would destroy the hole result of the first sort function.</p>