自定义迭代器

时间:2014-12-07 01:49:55

标签: c++ stl iterator

我已经实现了像这样的迭代器

template <typename GridT, 
          typename GridPtr,
          typename GridRef,
          template <typename> class ShapeT>
class GridIterator
{
public:
    typedef GridIterator<GridT, GridPtr, GridRef, ShapeT> Iterator;

    // Iterator traits - typedefs and types required to be STL compliant
    typedef std::ptrdiff_t            difference_type;
    typedef typename GridT::Element   value_type;
    typedef typename GridT::Element*  pointer;
    typedef typename GridT::Element&  reference;
    typedef size_t                    size_type;
    typedef std::forward_iterator_tag iterator_category;

    GridIterator(GridT& grid,
                 ShapeT<typename GridT::Resolution> shape,
                 Index iterStartIndex);

    ~GridIterator();

    Iterator& operator++();
    Iterator  operator++(int);

    typename GridT::Element& operator*();
    typename GridT::Element* operator->();

    bool operator==(const GridIterator& rhs) const;
    bool operator!=(const GridIterator& rhs) const;


private:

    GridT& grid_;
    ShapeT<typename GridT::Resolution> shape_;
    Index iterIndex_;
    Index iterIndexEnd_;

};

它与std :: generate和std :: find一起工作正常,但是当我将它与std :: max_element一起使用时,我得到了他的错误:

  

main.cpp:在函数'int main(int,const char **)'中:main.cpp:105:16:   错误:'iter'未在此范围内声明   /usr/include/c++/4.6/algorithm:63:0,                    来自./grid/Map_Grid.h:11,                    来自main.cpp:4:/usr/include/c++/4.6/bits/stl_algo.h:在函数'_FIter中   std :: max_element(_FIter,_FIter)[with _FIter =   Map :: GridIterator,Map :: Grid *,   Map :: Grid&amp;,Map :: Rectangle&gt;]':main.cpp:102:53:
  从这里实例化/usr/include/c++/4.6/bits/stl_algo.h:6243:4:   错误:使用已删除的函数'Map :: GridIterator,Map :: Grid *,Map :: Grid&amp;,   地图::矩形&GT;&安培;地图:: GridIterator,   Map :: Grid *,Map :: Grid&amp;,   Map :: Rectangle&gt; :: operator =(const Map :: GridIterator,Map :: Grid *,Map :: Grid&amp ;,,   Map :: Rectangle&gt;&amp;)'在./grid/Map_Grid.h:8:0中包含的文件中,                    来自main.cpp:4:./ grid / Map_GridIterator.h:17:8:错误:'Map :: GridIterator,Map :: Grid *,Map :: Grid&amp;,Map :: Rectangle&gt;&amp;   Map :: GridIterator,Map :: Grid *,   Map :: Grid&amp;,Map :: Rectangle&gt; :: operator =(const   Map :: GridIterator,Map :: Grid *,   隐式删除Map :: Grid&amp;,Map :: Rectangle&gt;&amp;)'   因为默认定义不正确:   ./grid/Map_GridIterator.h:17:8:错误:非静态引用成员   “地图::网格和放大器;地图:: GridIterator,   Map :: Grid *,Map :: Grid&amp;,   Map :: Rectangle&gt; :: grid_',不能使用默认赋值运算符

关于我做错了什么的任何想法?

1 个答案:

答案 0 :(得分:0)

由于引用成员

,因此不会为迭代器默认生成赋值运算符(max_element似乎需要)
GridT& grid_;

...无法更改为引用不同的GridT对象。解决此问题的一种简单方法是通过指针来保持网格。