1

我正在尝试将多边形拆分为一堆矩形。为此,我正在使用 boost 多边形库。当我尝试从用户那里获取输入(例如这里的向量中)时,程序给出了意想不到的结果,但是当硬编码(在代码中注释)给出了正确的结果时,相同的值。

#include <iostream>
#include <vector>
#include <boost/polygon/polygon.hpp>

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

int main() {

    typedef gtl::polygon_90_with_holes_data<int> Polygon;
    typedef gtl::polygon_traits<Polygon>::point_type Point;
    Point pts[7];
    std::vector <double> vec  {0.0,0.0, 0.0, 235.0, 170.0, 235.0, 170.0, 305.0, 310.0, 305.0, 310.0, 0.0, 0.0, 0.0};
  
    for (int i  = 0 ; i< 7 ; i++) {
        pts[i] = gtl::construct<Point>(vec[i],vec[i+1]);
    }

    /*
    pts[0] = gtl::construct<Point>(0.0 , 0.0) ;
    pts[1] = gtl::construct<Point>(0.0 , 235.0) ;
    pts[2] = gtl::construct<Point>(170.0 , 235.0) ;
    pts[3] = gtl::construct<Point>(170.0 , 305.0) ;
    pts[4] = gtl::construct<Point>(310.0 , 305.0) ;
    pts[5] = gtl::construct<Point>(310.0 , 0.0) ;
    pts[6] = gtl::construct<Point>(0.0 , 0.0) ;
    */

    Polygon poly;
    gtl::set_points(poly, pts, pts+7);

    std::vector< gtl::rectangle_data<int> > rects;
    get_rectangles(rects, poly);

    std::cout << rects.size() << " rectangle: \n";

    for(std::vector<gtl::rectangle_data<int> >::iterator it = rects.begin(); it !=
        rects.end(); ++it) {
            // Print out the corner coordinates
            std::cout << "x1: "<< gtl::xl(*it) << ", x2: " << gtl::xh(*it)
            << ", y1: "<< gtl::yl(*it) << ", y2: " << gtl::yh(*it) << std::endl;
    }
    return 0;
}

输出:

以向量为输入

0 rectangle:

具有硬编码值

2 rectangle: 
1: 0, x2: 170, y1: 0, y2: 235
x1: 170, x2: 310, y1: 0, y2: 305
4

1 回答 1

0

我建议避免问题并使代码更安全:

住在科利鲁

#include <boost/polygon/polygon.hpp>
#include <iostream>
#include <vector>

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

int main() {
    using Polygon = gtl::polygon_90_with_holes_data<int>;
    using Point   = gtl::polygon_traits<Polygon>::point_type;

    std::vector const vec{0,   0,   0,   235, 170, 235, 170,
                          305, 310, 305, 310, 0,   0,   0};
    assert(vec.size() % 2 == 0);

    std::vector<Point> pts;
    for (size_t i = 0; i + 1 < vec.size(); i += 2) {
        pts.emplace_back(vec[i], vec[i + 1]);
    }

    Polygon poly;
    gtl::set_points(poly, pts.begin(), pts.end());

    std::vector<gtl::rectangle_data<int>> rects;
    get_rectangles(rects, poly);

    std::cout << rects.size() << " rectangle: \n";

    for (auto& r : rects) {
        // Print out the corner coordinates
        std::cout << "x1: " << gtl::xl(r) << ", x2: " << gtl::xh(r)
                  << ", y1: " << gtl::yl(r) << ", y2: " << gtl::yh(r)
                  << std::endl;
    }
}

印刷

2 rectangle: 
x1: 0, x2: 170, y1: 0, y2: 235
x1: 170, x2: 310, y1: 0, y2: 305
于 2022-03-06T00:56:52.960 回答