到底什么是 OutputIterator 以及如何构建一个与 CGAL Kd_tree::search 一起使用的 OutputIterator?

Lui*_* E. 0 c++ iterator class kdtree cgal

我使用 CGAL 的 Kd 树实现以及模糊球体作为查询对象来获取以某个点为中心的半径球体中包含的点r_max。这是这个最小的工作示例:

    #include <CGAL/Simple_cartesian.h>
    #include <CGAL/Kd_tree.h>
    #include <CGAL/Search_traits_2.h>
    #include <CGAL/Fuzzy_sphere.h>
    #include <iostream>
    #include <fstream>

    typedef CGAL::Simple_cartesian<double>  K;
    typedef K::Point_2                      Point;
    typedef CGAL::Search_traits_2<K>        TreeTraits;
    typedef CGAL::Kd_tree<TreeTraits>       Kd_tree;
    typedef Kd_tree::Tree                   Tree;
    typedef CGAL::Fuzzy_sphere<TreeTraits>  Sphere;

    int main(int argc, char* argv[])
    {
        double r_max;
        Tree tree;

        /* ... fill the tree with points, set the value of r_max ...*/

        // Report indices for the neighbors within a sphere
        unsigned int   idc_query = tree.size()/2;           // test index
        Tree::iterator kti       = idc_query + tree.begin();                                                                                
        Sphere s_query(*kti, r_max);                            

        // Print points
        tree.search(std::ostream_iterator<Point>(std::cout, "\n"), s_query);

        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我从CGAL示例的Spatial_searching文件夹下的nearest_neighbor_searching.cpp文件中获取并修改了注释“Printpoints”下方的行(我的版本是3.9)。

问题是:有没有办法让我设置一个不同的OutputIterator(而不是std::ostream_iterator)来将指针/迭代器/句柄存储到各种容器中搜索结果的点,而不是将点的坐标打印到标准输出?谢谢。

Fer*_*yer 5

在C++标准库中,有五种迭代器:

  • 输入迭代器
  • 输出迭代器
  • 前向迭代器
  • 双向迭代器
  • 随机访问迭代器

欲了解更多信息,请访问cplusplus.com

在您的情况下,您需要一个Output iterator,即一个it可以递增 ( ++it) 和取消引用 ( *it) 以获得可写入的非常量引用的对象。

您可以使用以下命令创建一个输出迭代器,将写入其中的所有项目插入到容器的末尾std::back_inserter

#include <iterator>
#include <vector>

...

std::vector<Point> points;
tree.search(std::back_inserter(points), s_query);
Run Code Online (Sandbox Code Playgroud)