gpt4 book ai didi

boost 多边形序列化

转载 作者:行者123 更新时间:2023-12-01 19:45:26 26 4
gpt4 key购买 nike

我在我的项目中使用 boost 几何体,并且我需要序列化多边形。我一直在使用 boost 序列化,对于许多 boost 数据类型都没有问题,但 boost 几何图形目前似乎不支持序列化,因为我在序列化文件夹中找不到任何 header 。

有没有众所周知的方法可以实现这一点?

谢谢。

编辑:二进制序列化示例:Boost Polygon Serialization: Ring

最佳答案

我同意,奇怪的是Boost.Geometry不支持Boost.Serialization。可能很难支持所有可能的模板参数组合,或者可能他们不关心,因为 WKT 已经提供了。

至少在“默认”容器类型的情况下,添加此类功能很简单。下面的代码实现了它并且功能齐全。

下面我假设您使用自定义类(来自 Qt 的 QPoint)作为点类。其他点类型的代码几乎与我的相同。

首先,为 Point 类添加序列化:

#include <QPoint>

#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>

BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPoint, int, cs::cartesian, x, y, setX, setY);
typedef QPoint MyPoint;


namespace boost {
namespace serialization {

template<class Archive>
void serialize(Archive & ar, MyPoint& pt, const unsigned int version) {
ar & boost::serialization::make_nvp("x", pt.rx() );
ar & boost::serialization::make_nvp("y", pt.ry() );
}
} //namespace serialization
} //namespace boost

接下来,您将添加环形和多边形的序列化。在这里,我使用了以下事实:Ring 和 Polygon 本质上分别是点和环的 std::vector,并且 std::vector 的序列化内置于 Boost.Serialization 中。

#include <boost/serialization/vector.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/ring.hpp>

//change template flags as you are pleased but ring and polygon has to be
//in correspondence w.r.t. to "closed" and "clockwise" policies
typedef boost::geometry::model::ring<MyPoint, false, true> MyRing;
typedef boost::geometry::model::polygon<MyPoint, false, true> MyPolygon;

namespace boost {
namespace serialization {

//Default ring<MyPoint> simply inherits from std::vector<MyPoint>,
//its serialization is trivial and no implementation is needed.

//Default polygon<MyPoint> gives direct access to outer ring and the container of inner rings
template<class Archive>
void serialize(Archive & ar, MyPolygon& poly, const unsigned int version) {
ar & boost::serialization::make_nvp("outer", poly.outer());
ar & boost::serialization::make_nvp("inners", poly.inners());
}


} //namespace serialization
} //namespace boost

就是这样,你已经完成了,现在你可以像任何其他类一样使用 MyPolygon 和 Boost.Serialize:

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

void foo_out(std::ostream & oss, const MyPolygon & poly)
{
boost::archive::xml_oarchive oa(oss);
oa & BOOST_SERIALIZATION_NVP(poly);
}

void foo_in(std::istream & iss, MyPolygon & poly)
{
boost::archive::xml_iarchive ia(iss);
ia & BOOST_SERIALIZATION_NVP(poly);
}

享受吧!

关于 boost 多边形序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com