写一段以已知点p为起点的欧式聚类的c++代码
以下是一个简单的以已知点p为起点的欧式聚类的C++代码示例:
#include <iostream>
#include <vector>
#include <cmath>
struct Point {
double x;
double y;
};
double calculateDistance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return std::sqrt(dx * dx + dy * dy);
}
std::vector<std::vector<Point>> euclideanClustering(std::vector<Point>& points, double threshold) {
std::vector<std::vector<Point>> clusters;
std::vector<bool> visited(points.size(), false);
for (int i = 0; i < points.size(); ++i) {
if (visited[i]) {
continue;
}
std::vector<Point> cluster;
cluster.push_back(points[i]);
visited[i] = true;
for (int j = i + 1; j < points.size(); ++j) {
if (!visited[j] && calculateDistance(points[i], points[j]) <= threshold) {
cluster.push_back(points[j]);
visited[j] = true;
}
}
clusters.push_back(cluster);
}
return clusters;
}
int main() {
std::vector<Point> points = {{1.0, 2.0}, {2.0, 3.0}, {3.0, 4.0}, {5.0, 6.0}, {6.0, 7.0}, {7.0, 8.0}};
double threshold = 2.0;
std::vector<std::vector<Point>> clusters = euclideanClustering(points, threshold);
for (const auto& cluster : clusters) {
std::cout << "Cluster: ";
for (const auto& point : cluster) {
std::cout << "(" << point.x << ", " << point.y << ") ";
}
std::cout << std::endl;
}
return 0;
}
该代码定义了一个Point结构体来表示二维平面上的点,calculateDistance函数用于计算两个点之间的欧式距离,euclideanClustering函数实现了欧式聚类算法,接受一个点的向量和一个阈值作为输入,并返回一个二维向量,其中每个子向量表示一个聚类。main函数中定义了一些点和阈值,并调用euclideanClustering函数进行聚类,并打印每个聚类的点。
原文地址: http://www.cveoy.top/t/topic/hXQ3 著作权归作者所有。请勿转载和采集!