c++ 判断矩形是否有重叠
时间: 2024-03-27 16:39:52 浏览: 21
可以通过判断两个矩形是否相交来判断矩形是否有重叠。具体的做法是比较两个矩形的四个顶点的坐标,如果一个矩形的顶点坐标都在另一个矩形的外部,则两个矩形不相交,否则两个矩形相交。以下是一个简单的 C++ 实现:
```c++
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
struct Rectangle {
Point topleft; // 左上角坐标
Point bottomright; // 右下角坐标
};
bool isOverlap(Rectangle r1, Rectangle r2) {
// 如果一个矩形的所有顶点坐标都在另一个矩形的外部,则两个矩形不相交
if (r1.topleft.x > r2.bottomright.x || r1.topleft.y > r2.bottomright.y ||
r1.bottomright.x < r2.topleft.x || r1.bottomright.y < r2.topleft.y) {
return false;
}
return true;
}
int main() {
Rectangle r1 = {{1, 2}, {3, 4}};
Rectangle r2 = {{2, 3}, {4, 5}};
if (isOverlap(r1, r2)) {
cout << "The two rectangles overlap." << endl;
} else {
cout << "The two rectangles do not overlap." << endl;
}
return 0;
}
```
注意,这里假设矩形的边与坐标轴平行。如果矩形有旋转,则需要另外的算法来判断是否相交。