9

I have a group of coordinates for example :

10,40; 9,27; 5,68; 7,55; 8,15;

How do I sort those coordinates without losing the correct X-Axis of the sorted Y-Axis.

From the example above I want to sort the coordinates so the correct output will be:

8,15; 9,27; 10,40; 7,55; 5,68.

Any suggestion will be greatly appreciated. Thank you.

anarchy99
  • 993
  • 4
  • 14
  • 20

3 Answers3

21

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);
}
Alexey
  • 5,898
  • 9
  • 44
  • 81
  • Hi @Alex its very usefully but in my case gives error within algorithm.cpp class "No matching function for call for object of type myclass". – Madhubalan K Jan 08 '14 at 06:23
1

You need to specify how exactly you are storing your group of coordinates.

The easiest way is to store them as a new struct you create and apply a basic bubble sort algorithm over the top of it, using the Y value as your sort parameter. Then when you "swap" the position of the structs, the X & Y stay together.

struct Vector {
  float x;
  float y;
};
Mike D
  • 69
  • 1
  • 4
  • Thank you for your answer, actually I store the points with `std::vector`. Do you have any other suggestion besides storing it again in a `struct`? – anarchy99 May 28 '13 at 16:21
0

You could create a class that maps a coordinate, and if you are using STL as your Vector, you can use the sort method to sort your whole vector based on the Y coordinate.

Here and here are similar questions from stack.

Community
  • 1
  • 1
mrcaramori
  • 2,503
  • 4
  • 29
  • 47
  • Thank you for your suggestion, from the reference you posted may help me to solve the problem. I will try it first. – anarchy99 May 28 '13 at 16:23