{/'title/':/'C++ 使用 PCL 库判断点在 Kruskal 最小生成树中出现的次数/',/'description/':/'本代码使用 PCL 库实现 Kruskal 最小生成树算法,并判断给定点在生成树中出现的次数。如果次数超过 2 次,则将布尔变量 yes 设为 false。/',/'keywords/':/'PCL, Kruskal 最小生成树, C++, 点云, 生成树, 算法, 点出现次数/',/'content/':/'#include ///'iostream///'//n#include ///'pcl/point_types.h///'//n#include ///'pcl/point_cloud.h///'//n#include ///'pcl/features/normal_3d.h///'//n#include ///'pcl/io/pcd_io.h///'//n//n// 定义点类型//ntypedef pcl::PointXYZ PointT;//ntypedef pcl::PointCloud PointCloudT;//n//n// 定义边类型//nstruct Edge {//n int src, tgt; // 边的起始点和目标点//n float weight; // 边的权重//n//n // 构造函数//n Edge(int s, int t, float w) : src(s), tgt(t), weight(w) {}//n};//n//n// 定义比较函数用于边的排序//nbool compareEdges(const Edge& e1, const Edge& e2) {//n return e1.weight < e2.weight;//n}//n//n// 查找父节点//nint findParent(int x, std::vector& parent) {//n if (parent[x] == x)//n return x;//n return parent[x] = findParent(parent[x], parent);//n}//n//n// 判断是否在同一个连通分量中//nbool inSameComponent(int x, int y, std::vector& parent) {//n return findParent(x, parent) == findParent(y, parent);//n}//n//n// 合并两个连通分量//nvoid mergeComponents(int x, int y, std::vector& parent) {//n int px = findParent(x, parent);//n int py = findParent(y, parent);//n parent[px] = py;//n}//n//n// 判断点p在kruskal最小生成树内出现的次数是否大于2次//nbool isPointRepeated(const PointT& p, const PointCloudT::Ptr cloud, const std::vector& edges) {//n std::vector parent(cloud->size()); // 记录每个点的父节点//n for (int i = 0; i < parent.size(); i++)//n parent[i] = i;//n//n for (const auto& edge : edges) {//n // 获取边的起始点和目标点的索引//n int src_idx = edge.src;//n int tgt_idx = edge.tgt;//n//n // 判断点p是否在边的起始点和目标点之间//n if ((cloud->points[src_idx].x == p.x && cloud->points[src_idx].y == p.y && cloud->points[src_idx].z == p.z) ||//n (cloud->points[tgt_idx].x == p.x && cloud->points[tgt_idx].y == p.y && cloud->points[tgt_idx].z == p.z)) {//n // 判断点p是否已在同一个连通分量中//n if (inSameComponent(src_idx, tgt_idx, parent))//n return true;//n//n // 合并两个连通分量//n mergeComponents(src_idx, tgt_idx, parent);//n }//n }//n//n return false;//n}//n//nint main() {//n // 构建点云数据//n PointCloudT::Ptr cloud(new PointCloudT);//n cloud->width = 5;//n cloud->height = 1;//n cloud->points.resize(cloud->width * cloud->height);//n for (int i = 0; i < cloud->points.size(); i++) {//n cloud->points[i].x = i;//n cloud->points[i].y = i;//n cloud->points[i].z = i;//n }//n//n // 构建边集合//n std::vector edges;//n edges.push_back(Edge(0, 1, 1.0));//n edges.push_back(Edge(1, 2, 2.0));//n edges.push_back(Edge(2, 3, 3.0));//n edges.push_back(Edge(3, 4, 4.0));//n edges.push_back(Edge(4, 0, 5.0));//n//n // 对边按权重进行排序//n std::sort(edges.begin(), edges.end(), compareEdges);//n//n // 假设要判断的点为p//n PointT p;//n p.x = 1;//n p.y = 1;//n p.z = 1;//n//n // 判断点p在kruskal最小生成树内出现的次数是否大于2次//n bool yes = isPointRepeated(p, cloud, edges);//n//n std::cout << ///'Point is repeated: ///' << (yes ? ///'true///' : ///'false///') << std::endl;//n//n return 0;//n}/