Sort points by angle from given axis?

前端 未结 8 2715
無奈伤痛
無奈伤痛 2021-02-19 12:11

How can I sort an array of points/vectors by counter-clockwise increasing angle from a given axis vector?

For example:

8条回答
  •  青春惊慌失措
    2021-02-19 12:13

    Assuming they are all the same length and have the same origin, you can sort on

    struct sorter { 
        operator()(point a, point b) const {  
            if (a.y > 0) { //a between 0 and 180
                if (b.y < 0)  //b between 180 and 360
                    return false;
                return a.x < b.x; 
            } else { // a between 180 and 360
                if (b.y > 0) //b between 0 and 180
                    return true;
                return a.x > b.x;
            }
        }
        //for comparison you don't need exact angles, simply relative.
    }
    

    This will quickly sort them from 0->360 degress. Then you find your vector 0 (at position N), and std::rotate the results left N elements. (Thanks TomSirgedas!)

提交回复
热议问题