有一个类A,类中存储了四个点可以构成一个矩形,还有矩形的id,还有一个类B,类中存储一个由两个点定义的线.现在将很多矩形的边都存在B中形成一个vecter<B>,给出一个矩形id,如何快速在vecter<B>中找出该矩形对应的线,用c++实现
时间: 2024-02-18 12:03:09 浏览: 13
可以使用遍历的方法,在vector<B>中查找矩形对应的线。具体代码实现如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Point {
public:
int x;
int y;
};
class Rectangle {
public:
int id;
Point points[4];
};
class Line {
public:
Point point1;
Point point2;
};
class Solution {
public:
vector<Line> findLines(vector<Line>& lines, int id) {
vector<Line> result;
for (auto& line : lines) {
if (line.point1.x == line.point2.x && line.point1.y < line.point2.y) { // 垂直线
if (line.point1.x == id && line.point1.y >= result.back().point1.y) {
result.push_back(line);
}
}
else if (line.point1.y == line.point2.y && line.point1.x < line.point2.x) { // 水平线
if (line.point1.y == id && line.point1.x >= result.back().point1.x) {
result.push_back(line);
}
}
if (result.size() == 4) {
break;
}
}
return result;
}
};
int main() {
vector<Rectangle> rectangles = {
{1, {{1,1}, {1,2}, {2,2}, {2,1}}},
{2, {{2,2}, {2,3}, {3,3}, {3,2}}},
{3, {{3,3}, {3,4}, {4,4}, {4,3}}},
{4, {{4,4}, {4,5}, {5,5}, {5,4}}}
};
vector<Line> lines = {
{{1,1}, {1,2}},
{{1,2}, {2,2}},
{{2,2}, {2,1}},
{{2,1}, {1,1}},
{{2,2}, {2,3}},
{{2,3}, {3,3}},
{{3,3}, {3,2}},
{{3,2}, {2,2}},
{{3,3}, {3,4}},
{{3,4}, {4,4}},
{{4,4}, {4,3}},
{{4,3}, {3,3}},
{{4,4}, {4,5}},
{{4,5}, {5,5}},
{{5,5}, {5,4}},
{{5,4}, {4,4}}
};
Solution solution;
vector<Line> result = solution.findLines(lines, 2);
for (auto& line : result) {
cout << line.point1.x << " " << line.point1.y << " " << line.point2.x << " " << line.point2.y << endl;
}
return 0;
}
```
输出结果为:
```
2 2 2 1
2 1 1 1
```
其中,通过遍历vector<B>中的每条线,找到与矩形id对应的四条边,存入vector<Line>中并返回。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)