Advertisement
smatskevich

SortOperators

Oct 3rd, 2024
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct Point {
  6.   int x; int y;
  7.   int Dist2() const { return x * x + y * y;}
  8. //  bool operator<(const Point& right) const { return x < right.x; }
  9. };
  10. Point operator-(const Point& a, const Point& b) { return {a.x - b.x, a.y - b.y}; }
  11.  
  12. // 1. Оператор <
  13. bool operator<(const Point& left, const Point& right) { return left.x < right.x; }
  14.  
  15. void BubbleSort1(vector<Point>& v) {
  16.   int n = v.size();
  17.   for (int i = 0; i < n - 1; ++i) {
  18.     for (int j = 0; j < n - 1; ++j) {
  19.       if (v[j + 1] < v[j]) swap(v[j], v[j + 1]);
  20.     }
  21.   }
  22. }
  23.  
  24. // 2. Функция сравнения
  25. bool CompByDist(const Point& left, const Point& right) {
  26.   return left.Dist2() < right.Dist2();
  27. }
  28.  
  29. void BubbleSort2(vector<Point>& v, bool (* comp)(const Point&, const Point&)) {
  30.   int n = v.size();
  31.   for (int i = 0; i < n - 1; ++i) {
  32.     for (int j = 0; j < n - 1; ++j) {
  33.       if (comp(v[j + 1], v[j])) swap(v[j], v[j + 1]);
  34.     }
  35.   }
  36. }
  37.  
  38. // 3. Функтор
  39. struct CompByDistF {
  40.   Point center;
  41.   bool operator()(const Point& left, const Point& right) const {
  42.     return (left - center).Dist2() < (right - center).Dist2();
  43.   }
  44. };
  45.  
  46. template <class Comp>
  47. void BubbleSort(vector<Point>& v, Comp comp) {
  48.   int n = v.size();
  49.   for (int i = 0; i < n - 1; ++i) {
  50.     for (int j = 0; j < n - 1; ++j) {
  51.       if (comp(v[j + 1], v[j])) swap(v[j], v[j + 1]);
  52.     }
  53.   }
  54. }
  55.  
  56. int main() {
  57.   vector<Point> v = {{4, 2}, {3, 5}, {1, 9}, {7, 4}, {4, 3}};
  58.   // BubbleSort(v, CompByDist);
  59. //  CompByDistF compf;
  60. //  compf.center = {5, 5};
  61. //  BubbleSort(v, compf);
  62.   Point center = {5, 5};
  63. //  BubbleSort(v, [&center](const Point& left, const Point& right) {
  64. //    return (left - center).Dist2() < (right - center).Dist2();
  65. //  });
  66.  
  67.   sort(v.begin(), v.end(), [&center](const Point& left, const Point& right) {
  68.     return (left - center).Dist2() < (right - center).Dist2();
  69.   });
  70.   for (auto& p : v)
  71.     cout << p.x << " " << p.y << "\n";
  72.   return 0;
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement