如何从文件导入CGAL 2D General_polygon_2?编译报错求助
问题:CGAL
General_polygon_2 使用operator>>导入文本文件编译失败 根据CGAL文档说明,General_polygon_2可通过operator>>从文本文件导入数据,但以下代码无法编译:
#include <iostream> #include <fstream> #include <CGAL/Simple_cartesian.h> #include <CGAL/Gps_circle_segment_traits_2.h> #include <CGAL/General_polygon_2.h> using Kernel = CGAL::Simple_cartesian<double>; using PolygonTraits = CGAL::Gps_circle_segment_traits_2<Kernel>; using Polygon = CGAL::General_polygon_2<PolygonTraits>; int main() { Polygon pgn; std::ifstream fs("abc"); fs >> pgn; // <== 错误发生在此处 std::cout << pgn << std::endl; }
错误输出过长,无法完整展示。
环境信息:
- CGAL: 5.4.2
- 编译器: GCC 10.3.0
- 操作系统: Xubuntu 20.04.4
更新:CGAL 5.5中存在同样问题——X_monotone_curve_2类型无operator>>。
2024年4月11日更新:CGAL 6.0.1中该问题仍存在。
解答
问题根源在于你使用的Gps_circle_segment_traits_2特性类:General_polygon_2的operator>>依赖其特性类提供的X_monotone_curve_2类型的输入运算符,但Gps_circle_segment_traits_2并未为圆线段类型的X_monotone_curve_2实现operator>>。
CGAL文档中提到的General_polygon_2支持operator>>是有前提的:只有当特性类的X_monotone_curve_2类型本身提供输入运算符时,该功能才能正常工作。基于直线段的特性类(如Polygon_traits_2)通常默认实现了输入输出运算符,但圆线段这类曲线类型没有默认实现。
有两种可行的解决方式:
- 手动实现输入逻辑:自行读取文件中的圆线段参数(如圆心、半径、起止点/角度),构造
X_monotone_curve_2对象后逐个添加到General_polygon_2中。 - 替换特性类:如果业务场景允许使用直线段多边形,改用
Polygon_traits_2作为特性类,即可直接使用operator>>。
以下是手动实现输入的简化示例(假设文件每行存储圆心坐标、半径、起止角度):
#include <iostream> #include <fstream> #include <cmath> #include <CGAL/Simple_cartesian.h> #include <CGAL/Gps_circle_segment_traits_2.h> #include <CGAL/General_polygon_2.h> using Kernel = CGAL::Simple_cartesian<double>; using PolygonTraits = CGAL::Gps_circle_segment_traits_2<Kernel>; using Polygon = CGAL::General_polygon_2<PolygonTraits>; using Circle = typename Kernel::Circle_2; using Point = typename Kernel::Point_2; using X_monotone_curve = typename PolygonTraits::X_monotone_curve_2; int main() { Polygon pgn; std::ifstream fs("abc"); double cx, cy, r, start_rad, end_rad; // 注意:输入角度需为弧度制,若文件是角度需自行转换 while (fs >> cx >> cy >> r >> start_rad >> end_rad) { Circle circle(Point(cx, cy), r); Point start(cx + r * cos(start_rad), cy + r * sin(start_rad)); Point end(cx + r * cos(end_rad), cy + r * sin(end_rad)); X_monotone_curve seg(circle, start, end); pgn.push_back(seg); } std::cout << pgn << std::endl; }
注意:构造圆线段时需确保起止点在圆上,且线段满足X单调特性,否则可能触发CGAL的断言错误。
内容的提问来源于stack exchange,提问作者HEKTO
相关产品推荐
相关产品推荐

