Ordering Points based on their distance to each other ?

后端 未结 1 1347
孤独总比滥情好
孤独总比滥情好 2021-01-21 12:22

I have a vector of 3 Points A, B and C I want to order this vector based on the distance between those points, say the biggest distance is between B and C and than C and A and

1条回答
  •  逝去的感伤
    2021-01-21 13:02

    If the question is rephrased: Get all Manhattan distances between the points in a sorted vector:

    #include 
    #include 
    #include 
    
    struct Point { int x; int y; };
    struct ManhattanDistance {
        std::size_t a;
        std::size_t b;
    
        int value;
    
        ManhattanDistance(std::size_t index_a, const Point& a, std::size_t index_b, const Point& b)
        :   a(index_a), b(index_b), value(abs(b.x - a.x) + abs(b.y - a.y))
        {}
    
        operator int () const { return value; }
    };
    
    inline std::ostream& operator << (std::ostream& stream, const ManhattanDistance& x) {
        return stream << x.a << " - " << x.b << ": " << x.value;
    }
    
    int main()
    {
        typedef std::pair Pair;
        std::vector points = { {0,0}, {2,2}, {3,3}, {4,4}, {5,5} };
        std::vector distances;
        distances.reserve(points.size() * (points.size() - 1) / 2);
        for(std::size_t a = 0; a < points.size() - 1; ++a) {
            for(std::size_t b = a + 1; b < points.size(); ++b) {
                distances.push_back(ManhattanDistance(a, points[a], b, points[b]));
                std::cout << "Add: " << distances.back() << std::endl;
            }
        }
        std::sort(distances.begin(), distances.end(), std::greater());
        for(const auto& d: distances) std::cout << "Sorted: "  << d << '\n';
        std::cout << std::endl;
        return 0;
    }
    

    0 讨论(0)
提交回复
热议问题