How to sort the vector of points based on the y axis?

I have a group of coordinates, for example:

10.40; 9.27; 5.68; 7.55; 8.15;

How to sort these coordinates without losing the correct X axis of the sorted Y axis.

In the above example, I want to sort the coordinates so that the correct result is:

8.15; 9.27; 10.40; 7.55; 5.68.

Any suggestion would be greatly appreciated. Thanks.

+6
source share
3 answers

Documentation for std :: sort

#include "opencv2/core/core.hpp" #include <algorithm> // std::sort // This defines a binary predicate that, // taking two values of the same type of those // contained in the list, returns true if the first // argument goes before the second argument struct myclass { bool operator() (cv::Point pt1, cv::Point pt2) { return (pt1.y < pt2.y);} } myobject; int main () { // input data std::vector<cv::Point> pts(5); pts[0] = Point(10,40); pts[1] = Point(9,27); pts[2] = Point(5,68); pts[3] = Point(7,55); pts[4] = Point(8,15); // sort vector using myobject as comparator std::sort(pts.begin(), pts.end(), myobject); } 
+15
source

You need to specify exactly how you store your coordinate group.

The easiest way is to save them as the new structure you are creating and apply the basic algorithm for sorting bubbles on top of it, using the Y value as the sort parameter. Then, when you β€œchange” the position of the structures, X and Y stay together.

 struct Vector { float x; float y; }; 
+1
source

You can create a class that displays the coordinate, and if you use STL as your vector, you can use the sort method to sort the entire vector based on the Y coordinate.

Here and here, questions from the stack are similar.

0
source

Source: https://habr.com/ru/post/946026/


All Articles