理论上应该可以使用任何类型的空间索引或空间分区数据结构搜索最近的段。大多数情况下,此类空间索引的接口允许存储框(AABB)或点,因此在这些情况下,您将被迫存储段的边界框,然后在查询最近的框后再次检查相应的段。但是,可以直接索引段。例如,在 kd-tree 的情况下,它将是一个版本,其中包含定义分割平面和存储段的叶子的内部节点。
Boost.Geometry R-tree 支持Boost版本 1.56.0 及更高版本中的段。下面是使用此空间索引实现的 2d 段的示例:
// Required headers
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/segment.hpp>
#include <boost/geometry/index/rtree.hpp>
// Convenient namespaces
namespace bg = boost::geometry;
namespace bgm = boost::geometry::model;
namespace bgi = boost::geometry::index;
// Convenient types
typedef bgm::point<double, 2, bg::cs::cartesian> point;
typedef bgm::segment<point> segment;
typedef std::pair<segment, size_t> value;
typedef bgi::rtree<value, bgi::rstar<16> > rtree;
// Function object needed to filter the same segment in query()
// Note that in C++11 you could pass a lambda expression instead
struct different_id
{
different_id(size_t i) : id(i) {}
bool operator()(value const& v) const { return v.second != id; }
size_t id;
};
int main()
{
// The container for pairs of segments and IDs
std::vector<value> segments;
// Fill the container
for ( size_t i = 0 ; i < 10 ; ++i )
{
// Example segment
segment seg(point(i, i), point(i+1, i+1));
segments.push_back(std::make_pair(seg, i));
}
// Create the rtree
rtree rt(segments.begin(), segments.end());
// The number of closest segments
size_t k = 3;
// The container for results
std::vector< std::vector<value> > closest(segments.size());
for ( size_t i = 0 ; i < segments.size() ; ++i )
{
// Find k segments nearest to the i-th segment not including i-th segment
rt.query(bgi::nearest(segments[i].first, k) && bgi::satisfies(different_id(i)),
std::back_inserter(closest[i]));
}
// Print the results
for ( size_t i = 0 ; i < closest.size() ; ++i )
{
std::cout << "Segments closest to the segment " << i << " are:" << std::endl;
for ( size_t j = 0 ; j < closest[i].size() ; ++j )
std::cout << closest[i][j].second << ' ';
std::cout << std::endl;
}
}
如果您需要比某个阈值更接近的所有段,您可以使用迭代查询(示例)。