1

首先,我的意思是 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 类型,但我没有找到这样做的方法。谁能告诉我我该怎么做?

4

1 回答 1

1

严格来说,两个多边形的并集并不总是一个多边形(如果它们一开始是不相交的呢)。

如果您知道是这种情况,我建议您只获取集合的第一个多边形(也许断言集合的大小为 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() << "} ";
}

打印一样

于 2018-01-14T15:04:28.100 回答