Determine if two rectangles overlap each other?

前端 未结 23 876
礼貌的吻别
礼貌的吻别 2020-11-22 04:09

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectang

23条回答
  •  故里飘歌
    2020-11-22 05:10

    struct Rect
    {
        Rect(int x1, int x2, int y1, int y2)
        : x1(x1), x2(x2), y1(y1), y2(y2)
        {
            assert(x1 < x2);
            assert(y1 < y2);
        }
    
        int x1, x2, y1, y2;
    };
    
    bool
    overlap(const Rect &r1, const Rect &r2)
    {
        // The rectangles don't overlap if
        // one rectangle's minimum in some dimension 
        // is greater than the other's maximum in
        // that dimension.
    
        bool noOverlap = r1.x1 > r2.x2 ||
                         r2.x1 > r1.x2 ||
                         r1.y1 > r2.y2 ||
                         r2.y1 > r1.y2;
    
        return !noOverlap;
    }
    

提交回复
热议问题