记录在案的“用户定义的查询”中的最后一个示例显示了如何在谓词中使用 lambda。此 lambda 可以绑定范围内的其他变量,例如,您正在寻找其邻居的点。
这是一个小例子。该示例查找比 2 个单位更接近 (5, 5) 的点,以查找位于直线 上的点的集合y = x
。它应该很容易修改,以便首先检查所寻找的点是否在 R-tree 中,或者直接从 R-tree 中获取。
#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/index/rtree.hpp>
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
typedef bg::model::point<float, 2, bg::cs::cartesian> point;
typedef std::pair<point, unsigned> value;
int main(int argc, char *argv[])
{
bgi::rtree< value, bgi::quadratic<16> > rtree;
// create some values
for ( unsigned i = 0 ; i < 10 ; ++i )
{
point p = point(i, i);
rtree.insert(std::make_pair(p, i));
}
// search for nearest neighbours
std::vector<value> returned_values;
point sought = point(5, 5);
rtree.query(bgi::satisfies([&](value const& v) {return bg::distance(v.first, sought) < 2;}),
std::back_inserter(returned_values));
// print returned values
value to_print_out;
for (size_t i = 0; i < returned_values.size(); i++) {
to_print_out = returned_values[i];
float x = to_print_out.first.get<0>();
float y = to_print_out.first.get<1>();
std::cout << "Select point: " << to_print_out.second << std::endl;
std::cout << "x: " << x << ", y: " << y << std::endl;
}
return 0;
}
在 OS X 上使用通过 Macports 安装的 Boost 进行编译和运行:
$ c++ -std=c++11 -I/opt/local/include -L/opt/local/lib main.cpp -o geom && ./geom
Select point: 4
x: 4, y: 4
Select point: 5
x: 5, y: 5
Select point: 6
x: 6, y: 6