Determine if two rectangles overlap each other?

前端 未结 23 863
礼貌的吻别
礼貌的吻别 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 04:46

    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;
    };
    
    //some area of the r1 overlaps r2
    bool overlap(const Rect &r1, const Rect &r2)
    {
        return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&
               r1.y1 < r2.y2 && r2.x1 < r1.y2;
    }
    
    //either the rectangles overlap or the edges touch
    bool touch(const Rect &r1, const Rect &r2)
    {
        return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&
               r1.y1 <= r2.y2 && r2.x1 <= r1.y2;
    }
    

提交回复
热议问题