如何将 boost::polygon 中的 polygon_set_data 转换为 polygon_data?

How to convert a polygon_set_data in boost::polygon to polygon_data?

首先,我指的是 boost::polygon 图书馆,而不是 boost::geometry 图书馆。我的代码是:

namespace gtl = boost::polygon;
using namespace boost::polygon::operators;
typedef gtl::polygon_90_data<int> Polygon;
typedef gtl::polygon_traits<Polygon>::point_type Point;
typedef gtl::polygon_90_set_data<int> PolygonSet;
Point pts1[] = { Point(10000, 20000), Point(12000, 20000), Point(12000, 14000), Point(10000, 14000)};
Polygon poly1;
gtl::set_points(poly1, pts1, pts1 + 4);

Point pts2[] = { Point(11500, 18000), Point(11500, 25000), Point(14000, 25000), Point(14000, 18000)};
Polygon poly2;
gtl::set_points(poly2, pts2, pts2 + 4);

PolygonSet polyset;
assign(polyset, poly1 + poly2);

我想使用 poly1 和 poly2 的并集,它将是一个有 8 个点的多边形。现在我必须将结果 polyset 转换为 Polygon 类型,但我没有找到执行此操作的方法。谁能告诉我该怎么做?

两个多边形的并集严格来说并不总是一个多边形(如果它们一开始是分离的会怎样)。

如果您知道是这种情况,我建议只获取该集合的第一个多边形(也许断言该集合的大小为 1)。

std::vector<Polygon> v;
polyset.get_polygons(v);
if (v.size() == 1) {
    std::cout << "Union was: ";
    Polygon p = std::move(v.front()); // attempt to prevent copying
    for (auto& pt : p)
        std::cout << "{" << pt.x() << ", " << pt.y() << "} ";
} else {
    std::cout << "Something not quite right here\n";
}

Live On Coliru打印

Union was: {140, 180} {120, 180} {120, 140} {100, 140} {100, 200} {115, 200} {115, 250} {140, 250} 

奖金

我可能会这样写:

Live On Coliru

#include <boost/polygon/point_traits.hpp>
#include <boost/polygon/polygon.hpp>
#include <boost/polygon/polygon_set_data.hpp>
#include <boost/polygon/polygon_set_traits.hpp>
#include <boost/polygon/polygon_traits.hpp>

namespace gtl = boost::polygon;
using namespace boost::polygon::operators;

typedef gtl::polygon_90_data<int> Polygon;
typedef gtl::polygon_traits<Polygon>::point_type Point;
typedef gtl::polygon_90_set_data<int> PolygonSet;

Polygon make_polygon(std::initializer_list<Point> init) {
    Polygon p;
    p.set(init.begin(), init.end());
    return p;
}

template <typename P>
P get_union(P const& a, P const& b) {
    std::vector<P> v;
    PolygonSet(a+b).get(v);
    assert(v.size() == 1);
    return std::move(v.front());
}

int main() {
    Polygon u = get_union(
       make_polygon({ {100, 200}, {120, 200}, {120, 140}, {100, 140} }),
       make_polygon({ {115, 180}, {115, 250}, {140, 250}, {140, 180} }));

    for (auto& pt : u)
        std::cout << "{" << pt.x() << ", " << pt.y() << "} ";
}

打印相同