C++写一个类,传入一组三维点,和参考点,返回最短路线顺序点的代码
时间: 2024-05-05 17:15:25 浏览: 13
以下是一个示例代码,实现了一个类`ShortestPath`,其中包含了一个函数`find_shortest_path`,用于接收一组三维点和参考点,返回最短路线顺序点。
```c
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
struct Point3D {
double x, y, z;
Point3D(double x_, double y_, double z_) : x(x_), y(y_), z(z_) {}
};
class ShortestPath {
public:
vector<Point3D> find_shortest_path(const vector<Point3D>& points, const Point3D& ref) {
vector<Point3D> path = points;
sort(path.begin(), path.end(), [ref](const Point3D& a, const Point3D& b) {
return distance(ref, a) < distance(ref, b);
});
return path;
}
private:
double distance(const Point3D& a, const Point3D& b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2) + pow(a.z - b.z, 2));
}
};
int main() {
vector<Point3D> points = { Point3D(1, 2, 3), Point3D(4, 5, 6), Point3D(7, 8, 9) };
Point3D ref(0, 0, 0);
ShortestPath sp;
vector<Point3D> shortest_path = sp.find_shortest_path(points, ref);
for (const auto& p : shortest_path) {
cout << "(" << p.x << ", " << p.y << ", " << p.z << ")" << endl;
}
return 0;
}
```
在`ShortestPath`类中,`find_shortest_path`函数接收一组三维点和参考点`ref`,并返回按与参考点距离从小到大排序后的点的顺序。在实现中,我们使用了`sort`函数,其中的比较器使用了lambda表达式,以参考点为中心计算距离。
在`main`函数中,我们定义了一组三维点`points`和参考点`ref`,并使用`ShortestPath`类的实例`sp`来计算最短路线顺序点,最后输出结果。
相关推荐
![](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)
![](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)