Advertisement
Guest User

Coordinate Sorting with Function Objects

a guest
Jan 28th, 2020
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <ctime>
  4. #include <vector>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. class Coordinate
  9. {
  10.     double x, y;
  11. public:
  12.     Coordinate(double _x=0, double _y=0) :x(_x), y(_y) {}
  13.     double distance(Coordinate& c) { return sqrt(pow(c.x - x, 2) + pow(c.y - y, 2)); }
  14.     void print() { cout << "(" << x << "," << y << ")"; }
  15. };
  16.  
  17. class CompareCoords
  18. {
  19.     Coordinate ref;
  20. public:
  21.     CompareCoords(Coordinate c) :ref(c) {}
  22.     bool operator () (Coordinate& a, Coordinate& b) { return ref.distance(a) < ref.distance(b); }
  23. };
  24.  
  25. int main()
  26. {
  27.     vector<Coordinate> coords;
  28.     coords.reserve(20);
  29.     for (int i = 0; i < 20; ++i)
  30.         coords.push_back(Coordinate(rand() % 100, rand() % 100));
  31.     Coordinate me(0, 0);
  32.     sort(coords.begin(), coords.end(), CompareCoords(me));
  33.  
  34.     for (int i = 0; i < coords.size(); ++i)
  35.         coords[i].print();
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement