0

Suppose, i have 10 points with co-ordinates (x,y) .I have to sort those points in some manner (1) which x value is less than other it will be in earlier position than others (2) if x value of two points are the same then which y value is less than other will be in earlier position.So how can i sort these points?

Linkon Ruhul
  • 105
  • 1
  • 6
  • 5
    Besides reading a C++ book, I would look at the compare-function you can pass to sort(). – A.Franzen May 23 '16 at 08:53
  • [`std::pair`](http://en.cppreference.com/w/cpp/utility/pair) has provied `operator<` just working as you expect, so it should be fine to just use it. What problem did you encounter? – songyuanyao May 23 '16 at 08:54

2 Answers2

5

Simple:

#include <algorithm>
#include <utility>
#include <vector>


std::vector<std::pair<int, int>> points;

// populate

std::sort(points.begin(), points.end());
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So `std::pair` is ordered from first to second? – Andreas H. May 23 '16 at 08:59
  • 3
    @AndreasH. See [operator==,!=,<,<=,>,>=(std::pair)](http://en.cppreference.com/w/cpp/utility/pair/operator_cmp), "Compares lhs and rhs lexicographically, that is, compares the first elements and only if they are equivalent, compares the second elements." – songyuanyao May 23 '16 at 09:06
3

Use a lambda expression:

std::sort(pts.begin(), pts.end(), [](const auto& a, const auto & b) {
   return a.x < b.x || (a.x == b.x && a.y < b.y);
});

Not all compilers will accept auto as a lambda parameter type. So you may have to use the correct type name instead of auto.

If you are using a structure, a user defined less-than operator should help you:

struct Point 
{
    int x, y;
};

bool operator<(const Point& a, const Point& b)
{ 
    return a.x < b.x || (a.x == b.x && a.y < b.y);
}

To sort a std::vector<Point> according to your requirements, you just have to write

std::sort(pts.begin(), pts.end());

and it will use your user defined less-than operator.

Andreas H.
  • 1,757
  • 12
  • 24