天天看點

boost源碼學習之gemotry3:快速入門

boost gemotry

3.快速入門

這個快速入門展示了Boost.Geometry的一些特性,以帶注釋的相對簡單的代碼段的形式。

下面的代碼假設包含了boost/geometry.hpp,和使用了頭檔案boost::geometry。Boost.Geometry是盡頭檔案的,是以隻包含頭檔案就可以了。沒有必要與任何庫連結。

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

using namespace boost::geometry;
           

3.1笛卡爾

可以隻使用庫的一小部分。例如:兩點之間的距離是一個常見的用例。促進幾何體可以從各種類型計算它。使用它自己的類型之一:

model::d2::point_xy<int> p1(1, 1), p2(2, 2);
std::cout << "Distance p1-p2 is: " << distance(p1, p2) << std::endl;
           

如果包含右标題,并且類型綁定到坐标系,則可以使用其他各種類型作為點:普通C數組、Boost數組,Boost Tuple’s,Boost.Fusion,導入的結構,你自己的類。。。

注冊和使用C數組:

#include <boost/geometry/geometries/adapted/c_array.hpp>

BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)
           
int a[2] = {1,1};
int b[2] = {2,3};
double d = distance(a, b);
std::cout << "Distance a-b is: " << d << std::endl;
           

另一個常用的算法是point-in-polygon,在Boost.Geomety中由within函數實作。我們在這裡顯示他的用法,檢查一個Boost.Tuple(作為一個點)是否位于多邊形中,該多邊形由C數組點對填充。

但是首先要注冊一個Boost.Tuple,如同注冊C數組一樣:

#include <boost/geometry/geometries/adapted/boost_tuple.hpp>

BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
           
double points[][2] = {{2.0, 1.3}, {4.1, 3.0}, {5.3, 2.6}, {2.9, 0.7}, {2.0, 1.3}};
model::polygon<model::d2::point_xy<double> > poly;
append(poly, points);
boost::tuple<double, double> p = boost::make_tuple(3.7, 2.0);
std::cout << "Point p is in polygon? " << std::boolalpha << within(p, poly) << std::endl;
           

我們可以計算一個多邊形的面積:

根據模闆庫的性質,可以混合點類型。我們再次計算距離,現在使用一個C數組點和一個Boost元組點:

double d2 = distance(a, p);
std::cout << "Distance a-p is: " << d2 << std::endl;
           

上面列舉的代碼段産生如下輸出:

Distance p1-p2 is: 1.41421
Distance a-b is: 2.23607
Point p is in polygon? true
Area: 3.015
Distance a-p is: 2.87924
           

3.2非笛卡爾

也可以使用非笛卡爾點。例如:球體上的點。當使用諸如距離之類的算法時,庫“檢查”它是否在處理球形點,并計算球體上的距離,而不是應用畢達哥拉斯定理。

促進幾何體支援地理坐标系,但該坐标系位于擴充中,且未在目前的Boost版本中釋出。

我們将地球近似為一個球體,并計算阿姆斯特丹和巴黎之間的距離:

typedef boost::geometry::model::point
    <
        double, 2, boost::geometry::cs::spherical_equatorial<boost::geometry::degree>
    > spherical_point;

spherical_point amsterdam(4.90, 52.37);
spherical_point paris(2.35, 48.86);

double const earth_radius = 3959; // miles
std::cout << "Distance in miles: " << distance(amsterdam, paris) * earth_radius << std::endl;
           

3.3适應結構

最後是一個完全不同領域的示例:開發基于視窗的應用程式,例如使用QtWidgets。隻要Qt類在Boost中注冊。我們可以使用它們。例如,我們可以檢查兩個矩形是否重疊,如果重疊,則将第二個矩形移動到另一個位置:

QRect r1(100, 200, 15, 15);
QRect r2(110, 210, 20, 20);
if (overlaps(r1, r2))
{
    assign_values(r2, 200, 300, 220, 320);
}
           
如何在Boost中注冊QT類

3.4更多

在參考(reference)部分可以找到更多的例子。