Search code examples
c++sortingvectorcopying

Sorting Vector of Coordinates C++


I am trying to sort a vector of coordinates. The vector has pointers to these coordinates. I want to sort them by x and by y. What I am currently thinking of how to do this is as follows make two copies of the vector and then sort them. I am unsure of the following two things: 1) How to make a copy of a vector of pointers 2) How to sort both the points by x and y in the vectors and ensure also that they are properly sorted as follows (1,4),(1,5)

I have been reading and trying to figure out if there were any built in functions but I am not sure if for example sort function would correctly sort the x and y properly orderwise.

Here is what I have so far and any help would be appreciated.

typedef struct{double x; double y;) pt;
vector<pt*>v1;
vector<pt*>*v2 = v1;
// allocate memory for the points and push_back on the vector
the vector would have the following points {(1,7),(4,4),(1,3),(-2,4)}

When sorted it for x, it would be X={(-2,4),(1,3),(1,7),(4,4)} and Y={(1,3),(-2,4),(4,4),(1,7)}


UPDATE:

I am currently at this stage but it is still not working... :(

bool compare(pt* m1, pt* m2){return(m1->x <= m2->x) && (m1->y <= m2->y);}

vector<pt*>v1_x = v1;
sort(v1_x.begin(), v1_x.end(), comparer);

Solution

  • It's fairly easy using a custom comparator to do the dereferencing, as well as ready-made lexicographic tuple comparison:

    #include <algorithm>
    #include <tuple>
    #include <vector>
    
    struct pt { double x, double y };
    
    std::vector<pt*> v = /* ... */ ;
    
    auto x = v, y = v;   // copies
    
    std::sort(x.begin(), x.end(),
              [](pt * a, pt * b) -> bool
              { return std::tie(a->x, a->y) < std::tie(b->x, b->y); });
    
    std::sort(y.begin(), y.end(),
              [](pt * a, pt * b) -> bool
              { return std::tie(a->y, a->x) < std::tie(b->y, b->x); });
    

    Of course the objects pointed to by the pointers must live at least as long as you're using the pointers in v, x and y.