fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. class punto
  6. {
  7. private:
  8. int x;
  9. int y;
  10. public:
  11. punto() = default; // since you simply wanna initilize them
  12. ~punto(){}
  13. void setx(int xn){ x = xn;}
  14. void sety(int yn) { y = yn; }
  15.  
  16. bool operator<(const punto& obj)
  17. { return this->y < obj.y; }
  18. // define getters to access the private memebers
  19. const int& getX()const { return x; }
  20. const int& getY()const { return y; }
  21. // overload operator<< to print the object of this class
  22. friend std::ostream& operator<<(std::ostream& out, const punto& obj);
  23. };
  24. std::ostream& operator<<(std::ostream& out, const punto& obj)
  25. { return out << obj.getX() << " " << obj.getY(); }
  26.  
  27.  
  28. int main()
  29. {
  30. std::vector<punto> list;
  31. int x, y, n;
  32. punto p1;
  33.  
  34. std::cin >> n;
  35. for(int contador=0; contador<n; contador++)
  36. {
  37. std::cin >> x >> y;
  38. p1.setx(x);
  39. p1.sety(y);
  40. list.push_back(p1);
  41. }
  42. std::cout <<"w.r.t Ys" <<std::endl;
  43. // to sort w.r.t Ys: simply std::sort()
  44. std::sort(list.begin(), list.end());
  45. // now you can print the objects like this
  46. for(const punto& it: list) std::cout << it << std::endl;
  47.  
  48. std::cout <<"w.r.t Xs" <<std::endl;
  49. // to sort w.r.t Xs: std::sort() with lambda
  50. std::sort(list.begin(), list.end(),[](const punto& lhs, const punto& rhs)->bool
  51. { return lhs.getX() < rhs.getX(); });
  52.  
  53. for(const punto& it: list) std::cout << it << std::endl;
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 4520KB
stdin
6
2 1
5 8
7 3
0 1
7 0
1 1
stdout
w.r.t Ys
7 0
2 1
0 1
1 1
7 3
5 8
w.r.t Xs
0 1
1 1
2 1
5 8
7 0
7 3